Let's say I have this schema
{
jedi: [{
name:String
lightsaber_color:String
]}
}
I want to return all and only the names of them. I tried
Jedi.find({})
.select('jedi.name')
.exec(function (err, jedi) {
if (err) {
console.log("nothing found")
}
}
It returns me nothing, while this code returns me everything.
Jedi.find({})
.select('jedi')
.exec(function (err, jedi) {
if (err) {
console.log("nothing found")
}
}
I see that jedi is an array so I think that .select('jedi.name')
may not work for this reason.
What is the right syntax to do so?
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
Mongoose find() Certain Fields To filter object properties in mongoose, you can use the select() function on the query. The select() function allows you to select the fields you wish to return.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.
For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.
You can try with this
Jedi.find({}, {'jedi.name':1}, function (err, jedi) {
if (err) {
console.log("nothing found")
}
else{
console.log(jedi);
}
}
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