我知道用户的ID,我想知道他们的shoppingList中是否有与"name" = "foo"
匹配的值。这是我当前的查询,但它返回结果,即使名称不存在,我假设因为其中一个值存在。如果两个值都为真,我如何只返回结果?
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);
}
})
用户架构:
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 ]
}
});
答案 0 :(得分:1)
第二个参数应该是查询的一部分。
User.findOne({"_id": req.user._id, "groceryList": {"$elemMatch": {"name": ingredients.name[i]}}})
如上所述,写起来会更简单:
Users.findOne({"_id": req.user._id, "groceryList.name": ingredients.name[i] })