A part of @boehm_s answer that's viable and quite clear you can also create a multiple field index that you can use to find what you need. This kind of index is very useful if you want to perform a combined query approach, e.g. looking in more than one string
field if a passed parameters match their content or is contained into them. You can take a look at this doc page about Text Indexes. I don't know if you are using Mongoose
or not but this answer may be useful.
Pay attention to the fact that this approach of mine would return ALL the documents that contain, in one or both field,s the "word" you are looking for.
After the creation of the index on your fields
db.collection.createIndex(
{
name: "text",
location: "text"
}
)
Let's suppose you've named this index txtIndex
, then, you can do
Mongo Driver for Node Way
. . .
let userProjection = {
"name": 1,
"age": 1,
"location": 1
};
/**
* @param req Contains information to find a user
* @param req.findMe Contains name concatenated to location
*/
let findUsers = (req) => {
letUsers = db.collection('users');
return new Promise((resolve, reject) => {
User.findOne({'txtIndex': params.body.findMe}, {fields: userProjection},(err, user) => {
if (err) {
return reject({message: 'MongoDB Error', err: err});
}
if (!user) {
return reject({message: 'User not found!'});
}
return resolve(user);
});
});
}
Mongoose Way
let Users = require('./users-model.js);
/**
* @param req Contains information to find a user
* @param req.findMe Contains name concatenated to location
*/
let findUsers = (req) => {
Users.findOne({txtIndex: req.body.FindMe}).then( function (err, user) {
if (err) {
return reject({message: 'MongoDB Error', err: err});
}
if (!user) {
return reject({message: 'User not found!'});
}
return resolve(user);
});
}