【问题标题】:populate is not working as I expected填充没有按我预期的那样工作
【发布时间】:2012-12-28 13:18:32
【问题描述】:

请在我的代码下方找到

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 中的所有文档详细信息,但我得到一个 undefined..

请指出上面代码中的问题。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 2013-04-11
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多