0

请在我的代码下面找到

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 对应的文档 ID,我期待 TestDocAccess.documentId 中的所有文档详细信息,但我得到一个未定义的..

请指出我上面的代码有什么问题。

4

1 回答 1

0

为了populate('documentId')在您的示例中工作,引用TestDocAccess模型的集合中必须有一个文档,其中包含与模型集合匹配的_id(不是documentId您所期望的)。documentIdTestDocMaster

于 2012-12-28T05:18:32.330 回答