Changing data in mongoose document

17 views
Skip to first unread message

Justin Golden

unread,
Jul 4, 2013, 2:44:58 AM7/4/13
to mongoo...@googlegroups.com

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?

Hylke Bron

unread,
Jul 4, 2013, 4:21:43 AM7/4/13
to mongoo...@googlegroups.com
Hi,

This is a classic syntax error.
And what exactly is your var callback5 defined to, and user is never defined (in user.save)?

first of all, find returns an array of items, im not sure what your goal is, but when you're sure youll only get 1 element, you can either use findOne or try and get the first element of the result.

Look at this:

user.findOne({username:"somename",key:"somekey"},function(err, result){
 
if(err)
   
HandleError(err); // Handle the given error

 
if(!result)
   
HandleNoResult(); // No result found, do something with it (or not)

 
// Set the banned attribute for the document found
  result
.set("banned", true);
  result
.save(function(err, result){
   
// In the save (or update) callback for altered element
   
if(err)
     
HandleError(err); // Save did not execute well, for an error occurred

   
// If no error occurred, you can assume the result was saved correctly
    res
.json('yep');
 
});
});

I hope this helps a bit, but i think you dont quire understand working with mongoose yet.

Reply all
Reply to author
Forward
0 new messages