147 words
1 minute
Query a field for multiple values
Sometimes you need to query a field within your schema and match it to multiple values. I needed to do this when I had a function that needed to return all users who’s office matched either of the two values I provided.
$in Operator
The $in
operator is an operator in Mongo that will return a document for any of the values in the supplied array that return true;
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
Schema
'use strict'; //import dependency var mongoose = require('mongoose'); var Schema = mongoose.Schema; //create new instance of the mongoose.schema. the schema takes an //object that shows the shape of your database entries. var usersSchema = new Schema({ first: String, last: String, email: String, role: String, lastLogin: Date, office: String }); module.exports = mongoose.model("Users", usersSchema);
API
I’m skipping the bulk of the api and just showing the function
User.find({ 'office': { $in: [req.params.office, "Company"]} }
Query a field for multiple values
https://edwardbeazer.com/posts/query-a-field-for-multiple-values/