[英]mongoDB: Unable to obtain full object response when reference exists in the object
我正在嘗試使用find
查詢對象。 整個對象就像這樣
{
"_id" : ObjectId("5aaf4133b72ed853c09d60d9"),
"invoiceItems" : [
{
"$ref" : "JobsPostings",
"$id" : ObjectId("5aad26b6f78a341ef831b4f7"),
"price" : 15,
"publishDate" : ISODate("2018-03-17T00:00:00.000Z"),
"_id" : ObjectId("5aaf4133b72ed853c09d60db")
},
{
"$ref" : "JobsPostings",
"$id" : ObjectId("5aad27e4f78a341ef831b513"),
"price" : 20,
"publishDate" : ISODate("2018-03-17T00:00:00.000Z"),
"_id" : ObjectId("5aaf4133b72ed853c09d60da")
}
],
{...}
}
我正在嘗試獲取invoiceItems對象,該對象是:
"invoiceItems" : [
{
"$ref" : "JobsPostings",
"$id" : ObjectId("5aad26b6f78a341ef831b4f7"),
"price" : 15,
"publishDate" : ISODate("2018-03-17T00:00:00.000Z"),
"_id" : ObjectId("5aaf4133b72ed853c09d60db")
},
{
"$ref" : "JobsPostings",
"$id" : ObjectId("5aad27e4f78a341ef831b513"),
"price" : 20,
"publishDate" : ISODate("2018-03-17T00:00:00.000Z"),
"_id" : ObjectId("5aaf4133b72ed853c09d60da")
}
]
這是我的獲取代碼:
PostPaidInvoice.find({_id: { $in : [ObjectId("5aaf4133b72ed853c09d60d9")]}}).then(result => {
console.log(JSON.stringify(result[0].invoiceItems));
}).catch(err => {
console.log(err);
});
我收到的回復不包含price
和publishDate
結果:
[{"_bsontype":"DBRef","namespace":"JobsPostings","oid":"5aad26b6f78a341ef831b4f7"},{"_bsontype":"DBRef","namespace":"JobsPostings","oid":"5aad27e4f78a341ef831b513"}]
但是,如果我從引用ref
刪除美元符號($),則它將返回整個對象。
您只需要在找到條件后添加一個關鍵的invoiceItems: 1
:
PostPaidInvoice.find({
_id: {
$in: [ObjectId("5aaf4133b72ed853c09d60d9")]
}
}, { invoiceItems: 1, _id: 0 }).then(result => {
console.log(JSON.stringify(result[0].invoiceItems));
}).catch(err => {
console.log(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.