Reputation: 3977
I have the following Schema:
const userSchema = new Schema({
local: {
email: {type: String, unique: true, lowercase: true, trim: true, required: true},
password: {type: String, required: true},
},
Items: [{
name: {type: String, trim: true},
createdAt: {type: Date, default: Date.now, select: false}
}]
});
How do I query 'Items'
(which contains array of objects) based on a specific _id that I will receive from the url parameter?
I have many different variations, including one shown below, but they all seem to return the Items array containing all objects, instead of just a single object matching the id?
User.findById(req.user.id, {}, {"Items._id": req.params.id}, (err, result) => { ... }
Upvotes: 1
Views: 6439
Reputation: 75914
You will have to use $projection
to access element from embedded array. The query part finds the matching array element and replaces the placeholder $
with the array index of the matching element and projection part with $
will now use the placeholder value to project the array element as a response.
Mongo Shell Variant : db.users.findOne({_id:req.user.id, "Items._id": req.params.id},{"Items.$": 1})
Mongoose Variant: User.findOne({_id:req.user.id, "Items._id": req.params.id},{"Items.$": 1}, (err, result) => { ... }
Upvotes: 2
Reputation: 3187
What you're trying to do is query for a subdocument. Check out http://mongoosejs.com/docs/subdocs.html
You can do something like:
User.findById(req.user.id, (err, user) => {
let item = user.Items.id(req.params.id);
});
Upvotes: 0