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?

7 Answers 7

29

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

Sign up to request clarification or add additional context in comments.

3 Comments

This solved my problem for save() not persisting.
This is what i needed. my save() returns an object with the changes i make, but never persists. markModfied() solved my issue.
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.
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.

1 Comment

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

1 Comment

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

Comments

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 });
        });
      });

Comments

0

Using a error function helped me out!

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.