Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose not saving data with no error

I have this code

      User.findOne({ email: req.body.email }, function(err, user) {
        if (user) {
          return res.status(400).json([{ msg: 'The email address you have entered is already associated with another account.' }]);
        }
        user = new User({
          name: req.body.name,
          email: req.body.email,
          password: req.body.password,
          mobile: req.body.mobile
        });
        user.save(function(err) {
          res.json({ token: generateToken(user), user: user });
        });
      });

I tried sending a request with postman and I did get a response back with the user object which means there is no err in the save function

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJleGNlcHRpb25zLnNnIiwic3ViIjoiNTc5NWQ0NzQxYmEzZWQwODE1ZTgzY2NmIiwiaWF0IjoxNDY5NDM3MDQ0LCJleHAiOjE0NzAwNDE4NDR9.2otkcPkJgsXvR8QOHAojDJ5YCxR7Uc2E4ApS77T55F8",
  "user": {
    "__v": 0,
    "created_at": "2016-07-25T08:57:24.612Z",
    "updated_at": "2016-07-25T08:57:24.612Z",
    "name": "Test",
    "email": "[email protected]",
    "password": "$2a$10$3UmABiDPeo6iHZ.DFbwOO.1ANpUWQmwr86bYbTmRuFedsbDcE0bbC",
    "mobile": 12345,
    "_id": "5795d4741ba3ed0815e83ccf"
  }
}

However there is no entry of this inside my DB. I've check through my database with Robomongo and I'm sure that there is no data. What did I missed out?

like image 255
Exceptions Avatar asked Jul 25 '16 09:07

Exceptions


4 Answers

This doesn't relate to OP's specific situation but for others who are trying unsuccessfully to save after modifying a Mixed property of your object, you have to call markModified(path) to let Mongoose know that the property has changed.

person.anything = { x: [3, 4, { y: "changed" }] }; // anything is 'Mixed' in the schema
person.markModified('anything');
person.save(); // anything will now get saved

Check out the 'Mixed' section of the Mongoose docs here

like image 182
ahaurat Avatar answered Nov 12 '22 22:11

ahaurat


I know this sounds stupid, but Mongoose uses collection name in plural so

mongoose.model('User' ...

saves to users collection. I lost some hours before I refreshed the mongoDB client and realized that all my documents were in 'users' not in 'user'.

like image 42
László Matuska Avatar answered Nov 12 '22 22:11

László Matuska


For anyone else having this issue, your model's _id SchemaType must be of type ObjectId.

Suppose we have a schema and model defined as:

var userSchema = new mongoose.Schema({
  _id: mongoose.Schema.ObjectId,
  userID: Number,
  name: String
});

var Users = mongoose.model('collectionName', userSchema);

And we want to update the name of the user with userID 1234:

Users.findOne({userID: 1234}, function(err, user) {
    user.name = "Jane Doe";

    user.save(function(err) {
       // ...
    }
}

Mongoose will successfully update it by performing:

users.update({ _id: ObjectId("anObjectID") }, { '$set': { name: 'Jane Doe' } })

If we had set the SchemaType of _id to String in userSchema, it would've done this:

users.update({ _id: 'anObjectID' }, { '$set': { name: 'Jane Doe' } })
like image 21
Micah Benn Avatar answered Nov 13 '22 00:11

Micah Benn


Your arent handling error while saving the collection, replace your user.save function with

user.save(function(err){
      if(err){
           console.log(err);
           return;
      }

      res.json({ token: generateToken(user), user: user });
});

By this you will be able to track whether the data is saved or not and what can be the associated error.

like image 13
Ajitej Kaushik Avatar answered Nov 12 '22 22:11

Ajitej Kaushik