Mongoose not saving data with no error
Asked Answered
B

7

12

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?

Birkett answered 25/7, 2016 at 9:3 Comment(0)
S
13

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.

Smithy answered 25/7, 2016 at 9:17 Comment(1)
Thanks. I had a username field duplicate key error which does not exists in the schema. Dropped the collection and it works again. Didn't realize I wasn't catching the error.Birkett
A
28

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

Aisha answered 27/8, 2018 at 6:4 Comment(3)
This solved my problem for save() not persisting.Hearse
This is what i needed. my save() returns an object with the changes i make, but never persists. markModfied() solved my issue.Arlyne
This solved my issue as well. I was using nested Maps as opposed to Mixed. I was even checking isModified, which was returning true, and save wasn't giving any errors, but it still wouldn't persist. Using markModified was the only way to get it to work.Broyles
S
13

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.

Smithy answered 25/7, 2016 at 9:17 Comment(1)
Thanks. I had a username field duplicate key error which does not exists in the schema. Dropped the collection and it works again. Didn't realize I wasn't catching the error.Birkett
N
5

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'.

Nightrider answered 12/1, 2019 at 12:1 Comment(1)
wow, they also pluralize under the hood. 'person' -> 'people'. I have ran into so many issues with this library, I will never use it outside being paid to.Moldboard
D
1

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' } })
Damper answered 12/8, 2017 at 20:26 Comment(0)
A
0

i think this is prob Just try this , Change variable name of the user Object

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.' }]);
        }
        newUser = new User({
          name: req.body.name,
          email: req.body.email,
          password: req.body.password,
          mobile: req.body.mobile
        });
        newUser.save(function(err,saveUser) {
          res.json({ token: generateToken(saveUser), user: saveUser });
        });
      });
Ariel answered 25/7, 2016 at 9:10 Comment(0)
H
0

Using a error function helped me out!

 await user.save(function(err){
  if(err){
       console.log(err);
       return;
  }});
Handicapped answered 15/9, 2020 at 20:12 Comment(0)
M
0

The reason is that you don't have enough permissions in your database. No matter what solution you're using (in my case it was Atlas), I've set up everything such as "insert, read, delete" etc. except those. They're needed for mongoose to browse collections, create new etc.

Without it, got the same symptoms. The result with real (!) data but no reflection in the database. So my advice, check permissions.

enter image description here

Macmullin answered 13/2 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.