Reputation: 4238
I have a NodeJS app with a function that takes an id and returns an object from my MongoDB database corresponding to said id. The id could be matched to either _id (ObjectID) or external_id (string) in my model, why I want to filter out the object where id is equal to _id or equal to external_id. I wrote this code but it doesn't seem to work when I run it in NodeJS, however it works fine if I try it in mongo in the terminal:
myModel.findOne({$or: [{_id: my_id}, {external_id: my_id}]}, function (err, model) {
...
});
Since it works in the terminal I guess there could be an issue with the different types of the two model objects but I can't figure it out. my_id is a string.
Thanks for any suggestions. Mattias
Upvotes: 2
Views: 642
Reputation: 1203
You could use the toArray() function to convert the results obtained in the cursor to an array, and work with that more easily in your code.
myModel.findOne({$or: [{_id: my_id}, {external_id: my_id}]}).toArray(function (err, model) {
...
});
Upvotes: 0
Reputation: 1385
find will actually return a cursor, even when only one record matches, you will need to iterated through the cursor, try this:
myModel.find({$or: [{_id: my_id}, {external_id: my_id}]}).nextObject(function (err, model) {
...
}
Upvotes: 2