Laerion
Laerion

Reputation: 865

Sails.js with Mongo can't find by _id

I'm trying to find a record on Mongo using the _id of the collection. I pass the _id, I've tried as a String and as a ObjectId, and no one works. What is odd is that using findOne it returns a completely different record, with a different _id. If I use just find, with a where, gets ALL records, it doesn't filter anything at all.

If I search using another field, then it works and gets the correct record, but I want to do it using the _id field. This is what I've tried so far:

MyModel.findOne({where: {_id: new    ObjectId("57926086e2a4ff010eeb8c83")}}).exec(function (err, record){
  //record completely different
});

MyModel.findOne({where: {_id:"57926086e2a4ff010eeb8c83"}}).exec(function (err, record){
  //record completely different
});

MyModel.findOne({id: new    ObjectId("57926086e2a4ff010eeb8c83")}).exec(function (err, record){
  //record completely different
});

MyModel.findOne({id:"57926086e2a4ff010eeb8c83"}).exec(function (err, record){
  //record completely different
});

So, what am I doing wrong?, I can't figure it out. I know (think) that I can do it using "native", but is that the only way???

Thanks!

Upvotes: 1

Views: 2730

Answers (1)

Manuel Reil
Manuel Reil

Reputation: 508

Based on my experience of our sails.js app, only your last option should work.

  • When using sails.js and Waterline, you have to use id and NOT _id (your last option).
  • When using MongoDB native calls via Waterline, you have to use _id and a new ObjectId() (the query param in your first option).

Upvotes: 2

Related Questions