Abdul Rehman Sayed Abdul Rehman Sayed - 6 months ago 99
Node.js Question

MongoError : selector must be a valid JavaScript object

I am using mongodb driver for nodejs.

I am getting below error while updating a record.


{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}


Here is my script :

MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};

db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();

});
});


I can write the below line in mongo console & it works.

db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})

Answer

You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.

db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated) 
// collName need not pass in the update function.

Need to use

db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

Comments