Home > Enterprise >  MongoInvalidArgumentError: Selector must be a valid JavaScript object
MongoInvalidArgumentError: Selector must be a valid JavaScript object

Time:12-31

I have documents in my monogodb consists of username, password and array and the functionality of this method that it takes some sort of string and put it in the array using the session.username

however whenever I try to call it and run it it gives me

 MongoInvalidArgumentError: Selector must be a valid JavaScript object

exactly on line db.updateOne(.........

MongoClient.connect("mongodb://127.0.0.1:27017", function (err, client) {
    let db = client.db('MyDB').collection('FirstCollection');
    let username = req.session.username;
    db.findOne({username: username},function(err,result){ const list = result.list;
        let found = false;

        for (let i = 0; i < list.length; i  ) {
            if (list[i] == destination) {
                found = true;
            }
        }
        if (found) {
            alert("already on your want to go list!");
        } else {
            alert("added successfully");
            list.push(destination);
            db.updateOne(username, {$set: {list: list}}, function (err, res) {
                if (err) throw err;
            });
        }
    });});

I've tried to use update instead of updateOne and tried to create and new array update it and push it instead of the old one.

CodePudding user response:

The first argument to updateOne should be a Filter, but you are passing a bare username.

Use

db.updateOne({username: username}, {$set: {list: list}}, function (err, res) {

or

db.updateOne({username}, {$set: {list: list}}, function (err, res) {
  • Related