populate没有像我预期的那样工作

时间:2012-12-28 05:01:27

标签: node.js mongodb mongoose

请在我的代码下面找到

var mongoose = require('mongoose');
var util = require('util');

var db = mongoose.connect('mongodb://localhost:27017/prats', function(err) {
  if (err) throw err;}  //this does not get printed
);

mongoose.connection.on("open", function(){
  console.log("mongodb is connected")}  //this gets printed
);

var Schema = mongoose.Schema;


var TestDocumentAccessSchema = new Schema({
  documentId: { type: Schema.ObjectId },
  userId: { type : String }, // Can be an SSO or a group (DL) id
  userName: { type : String },
});

var TestDocumentMasterSchema = new Schema({
  documentId: { type: Schema.ObjectId, ref: 'TestDocumentAccess'},
  masterId: { type: Schema.ObjectId }
});

var TestDocAccess  = mongoose.model('TestDocumentAccess', TestDocumentAccessSchema);
var TestDocMaster = mongoose.model('TestDocumentMaster', TestDocumentMasterSchema);

var document = new TestDocAccess(
    { documentId: '50dc37d6022b2bdd07000004',
    userId : "1234",
    userName : "Test Name",
    }
);

document.save(function (err) {
  if (err) return handleError(err);

  var master = new TestDocMaster({
    documentId: "50dc37d6022b2bdd07000004",
    masterId: "50a5e7bcda3c4d557f00847a"    // assign an ObjectId
  });

  master.save(function (err) {
    if (err) return handleError(err);
        console.log("That's it save success!!....");

    TestDocMaster.find({'masterId': '50a5e7bcda3c4d557f00847a'})
    .populate('documentId')
    .exec(function(err, TestDocAccess) {
        //I want all the document row corresponding to the master Id
        console.log("=========Test Doc Master======" +util.inspect(TestDocAccess.documentId));
    });
  });
}) 

我有多个与主ID相对应的文档,我期待TestDocAccess.documentId中的所有文档详细信息,但我得到未定义 ..

请在上面的代码中指出我的错误。

1 个答案:

答案 0 :(得分:0)

要使populate('documentId')能够在您的示例中使用,必须在引用的TestDocAccess模型集合中包含_id(而不是documentId的文档。期待)匹配documentId模型集合中的TestDocMaster