[英]How to query for sub-document in an array with Mongoose
我有一個看起來像這樣的項目架構:
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
}
我想從“設備”數組中查詢一個 object。 我能夠添加、刪除和顯示該數組中的所有子文檔,但我發現很難獲得與數組中的 _id 標准匹配的單個 object。
我得到的最接近的是這個(我要求:'/:id/:deviceID/edit',其中“:id”是Project ObjectId。
let device = await Project.find("devices._id": req.params.deviceID).lean()
console.log(device)
這為我提供了以下信息:
[
{
_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
}
]
我知道這可能真的是微不足道的問題,但我已經測試了不同的解決方案,但似乎沒有什么對我有用。 感謝您的理解
這是您可以從設備數組中僅過濾單個 object 的方法:
Project.find({"devices._id":req.params.deviceID },{ name:1, devices: { $elemMatch:{ _id:req.params.deviceID } }})
您可以將$elemMatch
用於投影或查詢階段進入find
,無論您希望它如何工作:
db.collection.find({
"id": 1,
"devices": { "$elemMatch": { "id": 1 } }
},{
"devices.$": 1
})
或者
db.collection.find({
"id": 1
},
{
"devices": { "$elemMatch": { "id": 1 } }
})
使用 mongoose 是相同的查詢。
yourModel.findOne({
"id": req.params.id
},
{
"devices": { "$elemMatch": { "id": req.params.deviceID } }
}).then(result => {
console.log("result = ",result.name)
}).catch(e => {
// error
})
如果您希望單獨獲取設備,則需要使用聚合。 這將返回一個數組
Project.aggregate([
{ "$unwind": "$devices" },
{ "$match": { "devices._id": req.params.deviceID } },
{
"$project": {
name: "$devices.name",
// Other fields
}
}
])
您要么等待這個,要么在最后使用 use.then()。
或者您可以使用 findOne() 它將為您提供只有一個元素的 Project + 設備
或者查找,它將為您提供一個object
數組,其中包含項目的_id
和設備中的單個元素
Project.findOne({"devices._id": req.params.deviceID}, 'devices.$'})
.then(project => {
console.log(project.devices[0])
})
現在我解決了這個問題:
let project = await Project.findById(req.params.id).lean()
let device = project.devices.find( _id => req.params.deviceID)
它為我提供了我想要的東西,但正如你所見,我要求整個項目。 希望它不會在未來給我帶來任何持久的麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.