hex20dec
hex20dec

Reputation: 127

Why does Mongodb update work but mongoose doesn't?

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

Upvotes: 3

Views: 3442

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 5229

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

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

Upvotes: 1

Alexandru Olaru
Alexandru Olaru

Reputation: 7112

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.

Upvotes: 1

Related Questions