Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

above words for normals elements like uname and others. But for object ids(_id), ..

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

above line not giving error, it is showing correctly..

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

above also not giving error...

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

I have to store all those a,b,c,d... in some variable in some correct format, and have to do 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 thing is, I should get all items except those items with those _ids.

like image 743
user1305989 Avatar asked Apr 18 '12 11:04

user1305989


2 Answers

The way $nin works in mongo is that it takes an array of values to check.

The code: var string = a+","+b Doesnt make this a valid array. as you're creating a string with the value sdfsdznfsdz, u89tgngnfdb

So $nin is treating the array as that value, not the way you're trying to implement.

Solution to do what you want is to create an array with those 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 incase you're a tad hazy regarding arrays, I suggest having a read of this:

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

like image 122
Menztrual Avatar answered Nov 14 '22 21:11

Menztrual


Not able to comment yet, but just wanted to add here that new ObjectID() wasn't working for me, but new ObjectId() (lowercase d) did work. Hope this helps someone.

like image 24
wolstat Avatar answered Nov 14 '22 20:11

wolstat