Node.js mongodb update over ObjectID

I want to update my document but it doesn't work 100%.

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
  if(err) throw err;

 db = database;

});

      

My collection string looks like this:

{"_id": ObjectId ("53f9379ce9575bbe9ec29581"), "name: paco", "status: student"}

Now, if I want to update a line above the document, follow these steps:

db.collection('user', function(err,  collection){
                collection.update({'_id':ObjectID(req.session.loggedIn)}, {image : filename}, {w:1}, function(err, result){
                    console.log(result);

      

I get simply:

{"_id": ObjectId ("53f9379ce9575bbe9ec29581"), "image: filename"}

How can I do an update to get my data like this:

{"_id": ObjectId ("53f9379ce9575bbe9ec29581"), "name: paco", "status: student", "image: filename"}

+3


source to share


2 answers


Doing the update

way you did it will fetch the document in your collection with the specified _id

, then it will replace the content of that document with what you specified as the second parameter. In your case, it will fetch the document with _id

53f9379ce9575bbe9ec29581

and replace the existing fields with the field you passed in image:filename

(this means the existing fields will be removed as you noticed).

What you want to do is use the operator $set

. This statement will not touch the checked out document, but will only change the field you specified, or add it if it doesn't exist.



So your update command should look something like this:

db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){
    console.log(result);

      

+9


source


to update a record with _id



var ObjectID = require('mongodb').ObjectID; 
exports.updateUser = function(req, res) {

     var collection = db.collection('users');

     collection.update(where,  $set:req.body, function(err, result) {
         if (err) {
             console.log('Error updating user: ' + err);
             res.send({'error':'An error has occurred'});
         } else {
             console.log('' + result + ' document(s) updated');
             res.send(user);
         }
     });
 }

      

+1


source







All Articles