My model code:
var user = mongoose.Schema({
email: ....
password: .....
name : ...
company : ...
position : ....
phoneNumber : ...
signDate : Date,
friends: [{ type : mongoose.Schema.Types.ObjectId ,unique: true, ref: 'user' }],
accessToken: .....
});
And:
var friend = mongoose.Schema({
friends: [{ type : mongoose.Schema.Types.ObjectId ,unique: true, ref: 'user' }]
});
Using these two, I want to search for all the fields using a single keyword.
var fds = new Friend;
User.findOne({email : user.email})
.populate({
path : 'friends',
match : ''''empty''''
})
.exec(function (err, fd) {
if(!err){
fds = fd.friends;
res.render('account/friend', { layout: false, user: user, friends: fds });
}else{ console.log(err)}
});
I don't know what to put in that empty space.
var term = new RegExp(req.body.inputAll, 'i');
User.find().or([{ email: { $regex: term }},
{ name: { $regex: term }},
{ company: { $regex: term }},
{ position: { $regex: term }},
{ phoneNumber: { $regex: term }}])
Elsewhere this was the word OR search. But I don't know how to populate OR search, or other way besides to using the Match?
Mongoose's populate function doesn't execute directly in Mongo. Instead after the initial find query returns a set a documents, populate will create an array of individual find queries on the referenced collection to execute and then merge the results back into the original documents.
Mongoose has a more powerful alternative called populate() , which lets you reference documents in other collections. Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).
You can use $or
operator to OR the queries for match
. Something like this :
User.findOne({email : user.email})
.populate({
path : 'friends',
match : {
$or: [
{ email: { $regex: term }},
{ name: { $regex: term }},
{ company: { $regex: term }},
{ position: { $regex: term }},
{ phoneNumber: { $regex: term }}
]
}
})
.exec(function (err, fd) {
if(!err){
fds = fd.friends;
res.render('account/friend', { layout: false, user: user, friends: fds });
}
else{
console.log(err)
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With