Nodejs, mongodb - using $ nin or $ in for object identifiers or _id

I am using Nodejs database, mongodb . We can use $nin like this

 Model.find({ uname : { $nin : ["sachin","saurav"] } }.... 

above words for normal elements like uname and others. But for ids (_id) objects, ..

 Model.find({_id : {$nin : ["6534767457dfgbyb23","wtvwt3wy5etvdh"] } } ... 

Above the line that does not produce an error, it is displayed correctly.

 var ObjectID = require('mongodb').ObjectID; var a = new ObjectID("sdfsdznfsdz"); var b=new ObjectID("sdfjwneufhq2rfwefsd"); Model.find({_id : { $nin : [a,b] } }... 

the above also gives no error ...

The problem is that I cannot write manually like a, b, c, d ...

I need to save all these a, b, c, d ... in some variable in some correct format and do it like this:

 Model.find({_id : {$nin : variable } } 

or

 Model.find({_id : {$nin : [variable] } } 

I tried this

 var string = a+","+b //this didnt work, error : invalid object id var string = "nfw34qfhrs9"+","+"u89tgngnfdb" //this also same error var string = "\"jn4tr43r\"" + "," + "\"ansfuw37fe\"" //this also same error 

What should I do? the fact is that I have to get all the elements except those elements with _ids tags.

+6
source share
2 answers

The way $ nin in mongo is to check requires an array of values.

Code: var string = a+","+b Does not make this a valid array. since you are creating a string with the value sdfsdznfsdz, u89tgngnfdb

So, $ nin treats the array as that value, not how you are trying to implement.

The solution to do what you want is to create an array with these values.

So something like:

 var ids = new Array( new ObjectId("1124edcef241"), new ObjectId("56943decfeca845") ); // Dont put [ ] as a parameter. Just send a variable thats an array Model.find( {_id : { $nin : ids } } ); ... 

Just raise that you are a bit foggy regarding arrays, I suggest reading this:

http://www.w3schools.com/js/js_obj_array.asp

+9
source

Failed to comment, but just wanted to add here that new ObjectID() didn't work for me, but new ObjectID() (lowercase d) did work. Hope this helps someone.

+5
source

Source: https://habr.com/ru/post/913516/


All Articles