这是查询的样本集合,我想要下面给出的结果。如何issuedDevices
使用mongo / nodejs查询在集合的文档中显示设备的详细信息和用户的详细信息,请帮助:
1.收款用户
/* 0 */
{
"_id" : 1,
"name" : "Pradeep",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T00:03:32.350-06:30")
}
/* 1 */
{
"_id" : 2,
"name" : "Steve",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T00:04:02.362-06:30")
}
/* 2 */
{
"_id" : 3,
"name" : "Jonhy",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T00:04:30.834-06:30")
}
/* 3 */
{
"_id" : 4,
"name" : "Pinty",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T00:05:11.035-06:30")
}
2.收集设备:
/* 0 */
{
"_id" : 1,
"name" : "iPad",
"owner" : "james"
}
/* 1 */
{
"_id" : 2,
"name" : "iPhone",
"owner" : "Micheal"
}
3.收集issueDevices:
/* 0 */
{
"_id" : ObjectId("55602058a64447a5071a9a85"),
"userId" : 1,
"deviceId" : 1,
"isReturnd" : false,
"issuedDateTime" : ISODate("2015-05-23T00:08:16.354-06:30")
}
/* 1 */
{
"_id" : ObjectId("55602065a64447a5071a9a86"),
"userId" : 2,
"deviceId" : 1,
"isReturnd" : true,
"issuedDateTime" : ISODate("2015-05-23T00:08:29.355-06:30")
}
/* 2 */
{
"_id" : ObjectId("5560207da64447a5071a9a87"),
"userId" : 3,
"deviceId" : 1,
"isReturnd" : true,
"issuedDateTime" : ISODate("2015-05-23T00:08:53.615-06:30")
}
我想要如下所示的结果,如何issuedDevices
使用mongo / nodejs查询在集合的文档中显示设备的详细信息和用户的详细信息。
预期产量
[
{
"_id" : ObjectId("5560207da64447a5071a9a87"),
"userId" : 3,
"deviceId" : 1,
"userDetails":{
"_id" : 3,
"name" : "Jonhy",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T00:04:30.834-06:30")
}
"deviceDetails":{
"_id" : 2,
"name" : "iPhone",
"owner" : "Micheal"
},
"isReturnd" : true,
"issuedDateTime" : ISODate("2015-05-23T00:08:53.615-06:30")
}
]
产生期望结果的mongodb查询将使用游标的forEach()
方法遍历文档,并使用结果创建一个新文档,然后将其保存到同一集合中。以下为ID为3的用户演示了此操作:find()
db.issuedDevices
db.issuedDevices.find({"userId" : 3}).forEach(function (doc){
var userDetails = db.user.findOne({"_id": 3});
var deviceDetails = db.devices.findOne({"_id": doc.deviceId});
doc.userDetails = userDetails;
doc.deviceDetails = deviceDetails;
db.issuedDevices.save(doc);
})
查询issueDevices集合db.issuedDevices.find({"userId" : 3})
将产生:
/* 0 */
{
"_id" : ObjectId("5560207da64447a5071a9a87"),
"userId" : 3,
"deviceId" : 1,
"isReturnd" : true,
"issuedDateTime" : ISODate("2015-05-23T06:38:53.615Z"),
"userDetails" : {
"_id" : 3,
"name" : "Jonhy",
"email" : "[email protected]",
"createDate" : ISODate("2015-05-23T06:34:30.834Z")
},
"deviceDetails" : {
"_id" : 1,
"name" : "iPad",
"owner" : "james"
}
}
在Mongoose中,这可以通过在IssuedDevice模型中进行嵌套调用来实现,但是lean()
在启用了lean选项的情况下,查询返回的文档将用作普通javascript对象,而不是MongooseDocuments:
IssuedDevice.findOne({"userId" : 3}).lean().exec(function (err, doc) {
User.findOne({"_id": 3}).exec(function (err, user) {
Devices.findOne({"_id": doc.deviceId}).exec(function (err, device) {
doc.userDetails = user;
doc.deviceDetails = device;
console.log(doc); // <--- gives you the result
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句