0

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 ]
}
});
1
  • Try User.findOne({_id: user_id, "groceryList.name": "foo"}). $elemMatch might be a bit overkill for this since you're only trying to match the one field. Additionally, findOne expects a single argument, so if you want to use the original query, be sure to merge the two objects into a single argument. Commented Dec 19, 2017 at 2:18

1 Answer 1

1

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] })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.