2

我有一些如下所示的集合,其中包含关系,testMastertestDoc之间的关系在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 表中获取数据的最佳方法是什么。

4

2 回答 2

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 呈现到前端。但是,任何后续刷新都会正确呈现页面。

于 2013-10-08T00:26:20.670 回答
0

假设您的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
    });
于 2012-12-20T03:40:05.727 回答