3

When I query monodb shell, I AM able to update the document. This is the mongodb command I use: db.users.update({name:"bob"}, {$set: {email:"[email protected]} })

But when I try to update it with mongoose, it doesn't work. What am I missing??

This is the code in mongoose:

// Create the users schema

var userSchema = mongoose.Schema({ name: String, email: String }, {collection: "users"}); 

// Create a model

var userModel = mongoose.model("userModel", userSchema); 

// Update a document

userModel.update({name:"bob"}, {$set: {email:"[email protected]"}} ); 

2 Answers 2

1

You should wait for the callback to see if the operation was succesful or not

userModel.update({ name: "bob" }, {$set: { email:"[email protected]" }}, function (err, user) { if (err) return handleError(err); res.send(user); }); 

The mongoose is working asynchronously, you should wait for the response in the callback. There is also a synchrone way to do that but With node is not recommended you will block the stack.

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

2 Comments

I didn't need any callback and saw in the documentation that it's an optional parameter so I just dropped it. But apparently it's required. Mongoose's docs needs some updating. Thank you good sir!
At least in this way you can see the result of the update operation, indeed it could be other issues but if there was an error you will see it in the console of your node instance.
1

You can use this if you don't need the result in callback

userModel.update({name:"bob"}, {$set: {email:"[email protected]"}}).exec(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.