I know the User's ID, and I want to know if they have a value in their groceryList that matches "name" = "foo". Here is my current query, but it is returning result even though the name doesn't exist, I'm assuming since one of the values exists. How do I make it only return result if both values are true?
User.findOne( {"_id": req.user._id},{"groceryList": {"$elemMatch": {"name": ingredients.name[i]}}}, function(err, result) {
if(err) {
console.log(err);
}
else if(result) {
console.log(result);
}
})
User Schema:
var groceryListSchema = mongoose.Schema({
quantity: { type: Number, required: true },
measurement: { type: String, required: true },
name: { type: String, required: true }
});
var userSchema = new mongoose.Schema({
username: String,
password: String,
recipes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Recipe'
}
],
groceryList: {
type: [ groceryListSchema ]
}
});
User.findOne({_id: user_id, "groceryList.name": "foo"}).$elemMatchmight be a bit overkill for this since you're only trying to match the one field. Additionally,findOneexpects a single argument, so if you want to use the original query, be sure to merge the two objects into a single argument.