David
David

Reputation: 972

Determine if value exists in user's embedded document array

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 ]
}
});

Upvotes: 0

Views: 34

Answers (1)

russpol
russpol

Reputation: 116

the second argument should be a part of your query.

User.findOne({"_id": req.user._id, "groceryList": {"$elemMatch": {"name": ingredients.name[i]}}})

and as pointed out above it would be simpler to write:

Users.findOne({"_id": req.user._id, "groceryList.name": ingredients.name[i] })

Upvotes: 1

Related Questions