machu pichu machu pichu - 1 year ago 45
Node.js Question

Node.js mongodb update over ObjectID

I wanna update my Document but its not 100% working.

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

db = database;


My collection raw looks so:

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

Now if I want to update the raw over the Document as follow:

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

I am getting just:

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

How can I make a update to get my data like this??:

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

Answer Source

Doing an update the way you did it is going to retrieve the document in your collection with the specified _id, then it is going to replace the content of this document with what you specified as your second parameter. In your case, it will retrieve the document with _id 53f9379ce9575bbe9ec29581, and replace the existing fields with the field you passed, image:filename (that means the existing fields will be removed, as you noticed).

What you want to do is use the $set operator. This operator will not touch the document retrieved, but only modify the field that you specified, or add it if it does not 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){