Node.js 从mongo中的多个集合获取数据
我有一些集合,如下图所示,它们保存着关系,testMaster和testDoc之间的关系保存在testDocMaster中 例如:Node.js 从mongo中的多个集合获取数据,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一些集合,如下图所示,它们保存着关系,testMaster和testDoc之间的关系保存在testDocMaster中 例如: testMaster { _id: "Schema.Objectid", name: "String" //master name } testDoc { _id : Schema.ObjectId, name: "String", //doc name other datas } testDocMaster { masterId: "_id of the te
testMaster {
_id: "Schema.Objectid",
name: "String" //master name
}
testDoc {
_id : Schema.ObjectId,
name: "String", //doc name
other datas
}
testDocMaster {
masterId: "_id of the testMaster table",
docId : "_id of the above testDoc"
}
对于每一个主条目,我们期待着许多关系
如果我有masterId,从testDoc表中获取数据的最佳方法是什么。假设您的
testDocMaster
模式使用ObjectId
类型,而ref
其他两个集合您可以使用Mongoose的支持来帮助:
TestDocMaster.findOne({ masterId: masterId})
.populate('docId')
.exec(function(err, testDocMaster) {
// testDocMaster.docId is populated with the full testDoc for the
// matching _id
});
我用这个让它工作起来:
// GLOBAL ARRAYS FOR STORING COLLECTION DATA
var collectionOne = [];
var collectionTwo = [];
app.get('/', function(req, res){
MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) {
if(!err) {
console.log("We are connected");
}
db.collection("collectionOne", function(err, collection) {
collection.find().sort({order_num: 1}).toArray(function(err, result) {
if (err) {
throw err;
} else {
for (i=0; i<result.length; i++) {
collectionOne[i] = result[i];
}
}
});
db.collection("collectionTwo", function(err, collection) {
collection.find().sort({order_num: 1}).toArray(function(err, result) {
if (err) {
throw err;
} else {
for (i=0; i<result.length; i++) {
collectionTwo[i] = result[i];
}
}
});
});
// Thank you aesede!
res.render('index.html', {
collectionOne: collectionOne,
collectionTwo: collectionTwo
});
});
});
});
//用于存储集合数据的全局数组
var collectionOne=[];
var collectionTwo=[];
app.get('/',函数(req,res){
MongoClient.connect(“mongodb://localhost:27017/michael,函数(err,db){
如果(!err){
log(“我们已连接”);
}
db.collection(“collectionOne”,函数(err,collection){
collection.find().sort({order\u num:1}).toArray(函数(err,result){
如果(错误){
犯错误;
}否则{
对于(i=0;iRelation集合在MongoDB中通常是一种反模式。当您有一个n:m关系时,您应该向其中一个文档添加一个数组字段,该字段保存对另一个文档的引用。我知道当您使用关系数据库时,这听起来不直观。但MongoDB不是关系数据库。@Philipp这根本不是accurate语句。某些关系最好用嵌入式数组表示,而某些关系最好用链接的独立集合表示。有关解释,请参阅我的答案