我正在尝试使用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
中删除美元符号($),则返回整个对象。
答案 0 :(得分:0)
在查找条件后,您只需添加一个键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);
});