Mongoose instance .save() not working

I have the same problem. my problem was about changing an array inside db, then when I try to use .save(), it didn't understand that I changed any thing, then the .save() didn't work. I just use markModified() before use .save() and my problem become solved.

this is my code with problem: (not working)

club.members[index].name = new_name;
club.save();

this is my solved code: (working)

club.members[index].name = new_name;
club.markModified('members');
club.save();

enjoy!


This sounds nuts.. and I've been trying to work through this problem for hours. Looked at so many stack overflow posts.. it's unbelievable.

And you know what it was? I wasn't specifying the database at the end of the url.

So instead of

"mongodb://127.0.0.1:27017/test"

I had

"mongodb://127.0.0.1:27017

I wasted a whole day on this. I really wish I was given errors of some kind. Saving a record always returned ok. And in the database log, I was connecting ok. But I really needed to look at the details. Yes, it was connecting to the mongo instance, but not to the database itself. ugh!


Like Paul said. Most likely you are calling save on the 'req.user' object, which is not a Mongoose object. Make sure you are doing something like this:

//I am using your 'user' schema
var userModel = mongoose.model('User', user);
var User = mongoose.model('User');
var newUser = new User(req.user);
newUser.save(function(error, user){
   //your code
}

I am not going to delete this question because people may encounter this problem too. Actually problem was not related with MongoDb or Mongoose. When you call Object.save() responsibility chain is like below:

  1. Schema.pre("save")
  2. Save data to dabe
  3. Schema.post("save")

So if you block pre("save") and don't call next() handler you won't be able to save your document. This was my case, I forgot the next() call inside an if statement and tried to find the error for more than 3 hours.

user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
        next();
    }
}

When this.trial == true, next handler won't be reachable.

To prevent errors like this we should take care of branch coverage, reporters can show us untested codes. Your problem might be related with this too. Be sure you are calling next() if your document should be saved.

Fixed Version

user.pre("save", function(next) {
    if(!this.trial){
        //do your job here
    }
    next();
}