Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

node.js - How to query for sub-document in an array with Mongoose

I have a Schema of Project that looks like this:

const ProjectSchema = new mongoose.Schema({
name: {
    type: String,
    Required: true,
    trim: true
},
description: {
    type: String,
},

devices: [{
    name: {type: String, Required: true},
    number: {type: String, trim: true},
    deck: {type: String},
    room: {type: String},
    frame: {type: String}
}],

cables: {
    type: Array
},
user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
},
adminsID: {
    type: Array
},
createdAt: {
    type: Date,
    default: Date.now
}

I want to query an object from array of "devices". I was able to add, delete and display all sub-documents from this array but I found it really difficult to get single object that matches _id criteria in the array.

The closest I got is this (I'm requesting: '/:id/:deviceID/edit' where ":id" is Project ObjectId.

let device = await Project.find("devices._id": req.params.deviceID).lean()
console.log(device)

which provides me with below info:

[
{
_id: 6009cfb3728ec23034187d3b,
cables: [],
adminsID: [],
name: 'Test project',
description: 'Test project description',
user: 5fff69af08fc5e47a0ce7944,
devices: [ [Object], [Object] ],
createdAt: 2021-01-21T19:02:11.352Z,
__v: 0
}
]

I know this might be really trivial problem, but I have tested for different solutions and nothing seemed to work with me. Thanks for understanding

question from:https://stackoverflow.com/questions/65863539/how-to-query-for-sub-document-in-an-array-with-mongoose

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is how you can filter only single object from the devices array:

 Project.find({"devices._id":req.params.deviceID  },{ name:1,  devices: { $elemMatch:{ _id:req.params.deviceID } }})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...