简体   繁体   中英

Using Javascript arrray in mongodb update query with $in

I am trying to update all documents in my collection which have fields containing any one of the values in my javascript array. I keep getting a '$in needs an array' error. I do not understand how to convert the javascript object into an array that mongo will accept.

Here is my code for the node backend:

 MongoClient.connect(url, function(err, db) {
          if (err) throw err;
          var dbo = db.db("test");
          var myquery = { transferID: {$in: {idStore}}};
          var newvalues = {$set: {redAlert: "1"} };
          dbo.collection("myCollection").updateMany(myquery, newvalues,     function(err, res) {
            if (err) throw err;
            console.log(res.result.nModified + " document(s) updated");
            db.close();
          });
       });

Here is my array:

var idStore = [123, 456, 789]

There is no problem with your array, but the problem is with your query, you are passing idStore with curly braces ({}) , which makes it an object , thats why it sis throwing that error.

change your query to this and try :

var myquery = { transferID: {$in: idStore}};//without {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM