Reputation: 3253
I am new to mongoose mongodb, and am trying to update data stored. I have tried the example in the api here: http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate but don't seem to be doing it right. It says to query for data and update it, I can do:
Model.findOne({ name: 'borne' }, function (err, doc)
{
if (err) ..
doc.name = 'jason borne';
doc.save(callback);
});
I am doing this:
user.find({ 'username': Username, 'code': Key}, function(err, check){
var callback5;
if((String(check)) === "")
{
res.json('nope');
}
else
{
banned: true;
user.save(callback5);
res.json('yep');
}
})
It returns the resulting query data, but when I add the code to update the value of the boolean "banned", I get an error. What am I doing wrong?
Upvotes: 1
Views: 10293
Reputation: 3247
I'm assuming that the user
variable is a Model object, and that what you're trying to achieve is to find a single user with a given username and code, and set the banned property of that user to be true.
The first thing is that user.find
will return an array of users, not just a single user, so you'll want to use user.findOne
instead.
user.findOne({ username: Username, code: Key}, function(err, userDoc) {
if (err)
{
// TODO: Handle the error!
}
if (! userDoc)
{
res.json('nope');
}
else
{
userDoc.banned = true;
userDoc.save(function (err) {
if (err)
{
// TODO: Handle the error!
}
res.json('yep');
});
}
})
This queries the database for a single document that matches the username and code. If userDoc
is null, then res.json('nope')
will happen.
The code then sets the banned
property of userDoc
to be true, and then save the document back to the database. Because the save
function is asynchronous, you want to put the res.json('yep')
code in the callback, otherwise you won't know whether it actually happened or not.
I haven't put any actual error handling code in, I've left that for you to do, but you should always deal with any potential errors when using the standard callback pattern.
You could also achieve this using findOneAndUpdate
:
var conditions = { username: Username, code: Key };
var update = { banned: true };
user.findOneAndUpdate(conditions, update, function (err)
{
if (err)
{
res.json('nope');
}
else
{
res.json('yep');
}
})
Upvotes: 5