mongoose query same field with different values
Solution 1
You should use the MongoDB $in
operator -
mongoose.find({title: {$in: ['some title', 'some other title']}})
You provide an array to $in
operator and it will return all the documents which have an exact title in the array specified.
Solution 2
Found this in 2021 with the same question. It seems the $in operator is no longer necessary. As long as you pass find() an array of items, it will search for all of them.
Ex:
Furniture.find({
room: [ 'first_id', 'second_id' ]
})
This will return the documents where room is the first OR second id.
Can be written in a query string like:
?room=first_id&room=second_id
There's no parsing needed—Node parses this into an array automatically.
Solution 3
If you're building this off a URL query eg: http://url.com/posts?title=one
but with multiple values in the query here's an approach:
Use a separator like &
in your query like so http://url.com/posts?title=title&other%20title
Then setup your request function to operate with async:
eg. async function listPosts() {}
Then use the &
seperator to detect if it's a query for multiple items or not and set your query accordingly. So the whole query for a list post would look something like this:
async function listPosts(req, res, next) {
const urlParts = url.parse(req.url, true);
const { query } = urlParts;
// Check if URL query has & char and split into multiple query strings
const multiQuery = async () => {
// Return array of any query param values containing '&'
const mQueryArr = Object.values(query).filter(i => i.indexOf('&') > -1);
if (mQueryArr.length) {
Object.keys(query).forEach((key) => {
if (query[key].indexOf('&') > -1) {
// Split strings containing '&' and set query to search multiple using
// mongooses '$in' operator
const queries = query[key].split('&');
query[key] = { $in: queries };
}
});
}
};
await multiQuery();
Post.find(query)
.exec((err, posts) => {
if (err) {
return next(err);
}
return res.json({ posts });
});
}
Hope this helps someone as it took me a while to figure out the approach for a URL query with multiple queries for the same object key.
JohnSnow
Updated on May 16, 2021Comments
-
JohnSnow almost 3 years
Is there a way to user
mongoose.find({title:'some title'})
to query the same field with multiple values? For example something like thismongoose.find({title:'some title', title:'some other title'})
sends back only documents matchingtitle:'some other title
is there a way to accomplish this ?