![](/img/trans.png)
[英]How to get data from multiple collections in mongodb using mongoose?
[英]Get data from multiple collections in mongoose?
我有兩個集合,即Orders和Employee。 我首先使用客戶ID從某個客戶的Orders集合中查找所有訂單,然后需要使用結果中的字段來查找Employee集合中的數據。 我面臨的問題是我從Orders得到的結果是一個數組,所以我需要使用for循環遍歷它,然后在for循環內找到Employee數據。 訂單的第一部分可以工作,但第二部分並不總是我的0數組值。
async.waterfall([
function(callback) {
Order.find({ user_id: req.body.id}, {sort: { id: -1 }}, function(err, order) {
callback(null, order);
});
},
function(order, callback) {
for(var i = 0; i < order.length; i++) {
Employee.find({id: order[i].id}, 'field', function(err, employee) {
if (employee.length > 0) {
order[i].field = employee[i].field;
}
order[i].id = order[i].otherid;
regs.push(order[i]);
});
callback(null, regs);
}
}], function (err, result) {
res.send(result);
});
但結果是:[0],這不是預期的結果。 我在這做錯了什么? 還有其他解決辦法
您可以在mongodb中嘗試$ lookup。 我覺得對你很有幫助
我有這樣的訂單集合
{ "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }
{ "_id" : 3 }
另一個集合就是這樣的庫存
{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }
{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }
{ "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }
{ "_id" : 5, "sku": null, description: "Incomplete" }
{ "_id" : 6 }
我使用聚合找到所有的訂單數據,然后我需要找到使用指令集的現場庫存數據
db.orders.aggregate([
{
$lookup:
{
from: "inventory", //another collection name
localField: "item", // order collection field
foreignField: "sku", // inventory collection field
as: "inventory_docs"
}
}
])
產量
{
"_id" : 1,
"item" : "abc",
"price" : 12,
"quantity" : 2,
"inventory_docs" : [
{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }
]
}
{
"_id" : 2,
"item" : "jkl",
"price" : 20,
"quantity" : 1,
"inventory_docs" : [
{ "_id" : 4, "sku" : "jkl", "description" : "product 4", "instock" : 70 }
]
}
{
"_id" : 3,
"inventory_docs" : [
{ "_id" : 5, "sku" : null, "description" : "Incomplete" },
{ "_id" : 6 }
]
}
在這種情況下我會使用populate()
。 確實有點棘手,因為你沒有在這里發布你當前的模式,但我們假設你有一個這樣的設置:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
var orderSchema = new Schema({
user : { type: Schema.ObjectId, ref: 'User' },
employee : {type: Schema.ObjectId, ref: 'Employee' }
/* Other things */
});
mongoose.model('Order', orderSchema);
現在,根據設置,您可以這樣查詢:
Order.find({user: new ObjectId(req.body.id)}).sort({id:-1}).populate('employee').exec(function(e, orders){
/* whatever you want to do with the orders, each of which will have the employee data filled in by here */
});
如果您只想從Employee模型中提取一些字段,則可以像.populate('employee','name')
。 完整的文檔在mongoose網站上
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.