2

Please how do I go about retrieving records from MongoDB using mongoose where the Model ID doesn't match the given ID. The model is all setup properly. I am not entirely new to Node.js, mongoDB, Mongoose.

I tried using $ne:

var ID = ....

User.find({id: {$ne: ID}},
function(error, users) {
  console.log(users);
  callback(error, count);
});

I also tried using RegExp:

var regex = new RegExp('^((?!' + ID + ').)*$', "i");
User.find({id: regex},
function(error, users) {
  console.log(users);
  callback(error, users);
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
xdzc
  • 1,421
  • 1
  • 17
  • 23
  • 1
    Shouldn't it be `_id` instead of `id`? – JohnnyHK May 31 '15 at 00:50
  • What does the document you want to find look like? JohnnyHK's point about `_id` seems like a good bet, but its hard to help when we can't see what you're searching for. – Aaron Dufour May 31 '15 at 01:07
  • @JohnnyHK a string equivalence of _id is exposed as id (virtual field) in mongoose models – xdzc May 31 '15 at 14:29
  • @AaronDufour What am searching for is not really important. Just trying to get all records (documents) not matching the dynamically passed in ID (string) – xdzc May 31 '15 at 14:35
  • 2
    @czprobity You can't query against virtual fields like `id`, that's why it needs to be `_id` instead. But using `$ne` is correct, and `ID` can be a string as Mongoose will cast it to an `ObjectId` for you based on the schema. – JohnnyHK May 31 '15 at 14:38

2 Answers2

7

As JohnnyHK and Aaron Dufour have commented, you need to use _id instead of id.

Further, Mongo is expecting an Object and not a String when you query by _id.

You can require the native mongodb drivers ObjectID and use it in your code like this:

var ObjectID = require('mongodb').ObjectID;

_id = new ObjectID('stringId');

User.find({'_id': {$ne: _id}},
function(error, users) {
  console.log(users);
  callback(error, count);
});

See this answer.

Community
  • 1
  • 1
Michael
  • 104
  • 3
  • Yeah, thats why i queried by `id` not `_id`. Also i tried this method and it didn't work. It threw an exception when the argument for `new ObjectId` is not a 24 byte hex string, 12 byte binary string or a Number as specified [here](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html) – xdzc May 31 '15 at 14:57
  • This did not work for me too, but the solution by @czprobity worked. $ne worked only with string ID not object id for some reason. – Sharjeel Ahmed Nov 25 '16 at 14:01
2

Thanks guys, I was finally able to get it working by doing this:

var id = .... (string type)
User.find({_id: {$ne: id}}, 
  function(error, users) {
    console.log(users);
    callback(error, users);
  }
);

The string idis implicitly cast to ObjectId before the comparison. The downside of this is a CastError is thrown when the string id is not a string representation of an ObjectId. The cast will fail.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
xdzc
  • 1,421
  • 1
  • 17
  • 23