从mongo中的多个集合中获取数据

时间:2012-12-20 03:26:36

标签: 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 testMaster table",
docId : "_id of the above testDoc"
}

对于每个主条目,我们期待很多关系,

如果我有masterId,那么从testDoc表中获取数据的最佳方法是什么。

2 个答案:

答案 0 :(得分:1)

我用它来工作:

// 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
      });
    });
  });
});

现在,出于某种原因,当Node重新启动时,我点击刷新,它不会将HTML呈现在前端。但是,任何后续刷新都会正确呈现页面。

答案 1 :(得分:0)

假设您的testDocMaster架构使用了ObjectId种类ref其他两个集合,您可以使用Mongoose的query population支持来帮助解决此问题:

TestDocMaster.findOne({ masterId: masterId})
    .populate('docId')
    .exec(function(err, testDocMaster) {
        // testDocMaster.docId is populated with the full testDoc for the
        // matching _id
    });