我正在使用node.js工作mongodb連接查詢,我有兩個集合,我想加入兩個集合並希望填充數據。如何使用node.js連接Mongodb中的集合?
飲料收集
[{
"_id": "580a2f7615a0161010a23bfg",
"name": "Pepsi",
"createDate": "2016-10-21T15:08:27.405Z"
}, {
"_id": "580a2f7615a0161010bge345",
"name": "Mirinda",
"createDate": "2016-10-21T15:08:27.405Z"
}, {
"_id": "580a2f7615a0161010vbgdt5",
"name": "Coke",
"createDate": "2016-10-21T15:08:27.405Z"
}, {
"_id": "580a2f7615a0161010vb9876",
"name": "Thums Up",
"createDate": "2016-10-21T15:08:27.405Z"
}, {
"_id": "580a2f7615a0161010vbgmnk9",
"name": "Slice",
"createDate": "2016-10-21T15:08:27.405Z"
}]
指令集
[{
"_id": "580fa9a92bb22e783b298798",
"created_at": "2016-10-25T18:41:53.716Z",
"tab": [{
"created_at": "2016-10-26T00:21:33.100Z",
"cost": 30,
"quantity": 7,
"name": "Mirinda"
}]
},
{
"_id": "580fa9a92bb22e783b29887h",
"created_at": "2016-10-25T18:41:53.716Z",
"tab": [{
"created_at": "2016-10-26T00:21:33.100Z",
"cost": 25,
"quantity": 5,
"name": "Pepsi"
}]
}]
所以我想通過加入飲料收集找到指令集的名稱。
訂單模式
var mongoose = require("mongoose");
var OrderSchema = new mongoose.Schema({
tab: [{
quantity: Number,
cost: Number,
name: {
type: String
},
created_at: {
type: Date
}
}],
});
module.exports = mongoose.model("Order", OrderSchema);
飲料架構
var mongoose = require('mongoose'),
utilities = require('../config/utilities');
var DrinkSchema = mongoose.Schema({
drinks_name: { type: mongoose.Schema.Types.ObjectId, ref: 'Order' },
name: {
type: String
},
id: {
type: String
},
createDate: {
type: String
},
})
module.exports = mongoose.model("Drinks", DrinkSchema);
Node.js的代碼
var Drinks = require("../models/drinks"),
Orders = require("../models/orders"),
async = require('async'),
mongoose = require('mongoose');
exports.getOrdersList = function(req, res) {
//How to Join Drinks and Orders Collection ?
Drinks
.find({})
.populate('drinks_name', 'tab.name')
.exec(function (err, result) {
console.log('The Drinks List is', result);
});
}
敬請通過我上面的帖子,讓我知道,如果您有任何解決方案。
我不確定在MongoDB中是否有允許連接的內置功能。 – Thilo
嘿我猜聚合查詢將工作 –
通過代碼執行加入或檢查貓鼬引用和人口。 – qqilihq