【发布时间】:2016-02-22 14:03:04
【问题描述】:
感谢阅读。我正在尝试使用 NodeJS 中的 mongoose 模块获取存储在 mongodb 数据库中的大量数据,以显示在前端。我想知道解决这个问题的最佳方法是什么?我的数据看起来像这样...
系列 1:洞穴
{
"_id" : ObjectId("564d2f6eb0896138247ff791"),
"name" : "ACME Cave",
"slug" : "acme-cave",
"timeCreated" : ISODate("2015-11-19T02:09:50.492+0000"),
"address" : {
"county" : "Somewhere",
"state" : "CA",
"country" : "USA"
}
}
集合 2:位置
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 54.5793621,
"longitude" : -74.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
}
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 48.5783611,
"longitude" : -72.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
}
我想像这样将一些子字段合并到父字段中......
{
"_id" : ObjectId("564d2f6eb0896138247ff791"),
"name" : "ACME Cave",
"slug" : "acme-cave",
"timeCreated" : ISODate("2015-11-19T02:09:50.492+0000"),
"address" : {
"county" : "Somewhere",
"state" : "NY",
"country" : "USA"
},
locations: [
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 54.5793621,
"longitude" : -74.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches doc collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
},
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 48.5783611,
"longitude" : -72.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches doc collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
}
]
}
我在下面有这个 sn-p 可以完成这个,但它似乎不正确。有没有人对这样做有任何见解?
Parent.find({}, {'locations': 1}).stream().on('data', function(parent) {
// add the location to the parent doc
Child.find({parent_id: {$in: parent._id}}, {'latitude': 1, 'longitude': 1}, function(err, child) {
parent.locations = child;
console.log(parent);
});
});
这将返回以下 JSON,这与我的输出相同..
{
"_id" : ObjectId("564d2f6eb0896138247ff791"),
"name" : "ACME Cave",
"slug" : "acme-cave",
"timeCreated" : ISODate("2015-11-19T02:09:50.492+0000"),
"address" : {
"county" : "Somewhere",
"state" : "NY",
"country" : "USA"
},
locations: [
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 54.5793621,
"longitude" : -74.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches doc collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
},
{
"_id" : ObjectId("564d2f6fb0896138247ff855"),
"latitude" : 48.5783611,
"longitude" : -72.9669167,
"parent_id" : ObjectId("564d2f6eb0896138247ff791"), <-- matches doc collection 1
"timeCreated" : ISODate("2015-11-19T02:09:51.413+0000"),
}
]
}
我曾考虑将这些模式汇总到 1 个集合中,但由于我将添加到代码中的其他功能(例如存储图片和每个孩子的编辑),我不能。我认为使用单个集合并不明智,因为我会在文档中存储太多信息。
感谢您的帮助!
【问题讨论】:
标签: json node.js mongodb mongoose