Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

Can't get $or query to work in NodeJS with Mongoose

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

Answers (2)

Anuj Pancholi
Anuj Pancholi

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

Jesus Ruiz
Jesus Ruiz

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

Related Questions