I have a problem with Mongoose and MongoDb
It is very interesting that only Model.update
works and save
never works and does not even fire
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
}
Just in case this happens to anyone else.
Another cause of this could be if you do not have an open connection to your mongodb instance. Check your output for the appropriate connection feedback.
[initandlisten] connection accepted from 127.0.0.1:40448 #1 (1 connection now open)
I came across the same issue, turns out that instance.save()
returns a promise. So all you need to do is handle the promise.
Using async/await
-
await instance.save()
for anyone having same error as me.. If you call .save() twice in very short time. the last call will be discarded. My problem was this.
//module usersave(userData)
{
await userData.save()
}
//module A
{...todos
moduleB(userData)
...some todos that doesn't take much time.
await usersave(userData) //second call
}
//module B(userData)
{
...todos;
await usersave(userData) // first call
}
=> Object.save() was called at module B, and instantly called again at module A. (it doesn't matter you made save module or just directly called Object.save() ). these kinds of call stack emits no error, and normal success return on both modules. However, since second call is evoked before the mongodb actually reflects the change, later call is just discarded. problem is that it returns as if they are actually saved so you can't catch an error.
solution : just put an await. await new Promise(r=>setTimeout(r,2000)) will do.
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!