node.js - mongodb填充方法不起作用

标签 node.js mongodb model populate auto-populate

这是我的模型代码

var postSchema = new mongoose.Schema({
created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true },       //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});

var userSchema = new mongoose.Schema({
    username: String,
    password: String, //hash created from password
    created_at: {type: Date, default: Date.now}
});

下面是我如何插入数据并尝试使用填充方法检索它的代码。

Post.create({text: 'farheen123',created_by: '5587bb520462367a17f242d2'}, function(err, post){
if(err) console.log("Farheen has got error"+err);
else console.log(post);
});

//5587f5556e6f2b38244d02d1: 已创建用户的_id

        Post
        .findOne({ _id: '5587f5556e6f2b38244d02d1' })
        .populate('created_by')
        .exec(function (err, story) {
          if (err) return handleError(err);
          console.log('The creator is %s', story);
          // prints "The creator is Aaron"
        });

我得到的结果如下。它为 created_by 提供 numm 引用,而不是提供该 ID 的用户名和密码。

The creator is { _id: 5587f5556e6f2b38244d02d1,
  text: 'farheen123',
  created_by: null,
  __v: 0,
  created_at: Mon Jun 22 2015 17:15:25 GMT+0530 (IST) }

最佳答案

当您创建 Post 模型的实例时,您需要将来自用户的 _id 分配为 ObjectId,而不是字符串:

var ObjectId = require('mongoose').Types.ObjectId; 
Post.create({
    text: 'farheen123',
    created_by: new ObjectId('5587bb520462367a17f242d2')
}, function(err, post) {
   if(err) console.log("Farheen has got error"+err);
   else console.log(post);
});

关于node.js - mongodb填充方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979847/

相关文章:

Web 套接字服务器中的 JSON 解析

javascript - 将 JSON 文件保存到express( Node )中的服务器

mongodb - 如何对数组字段中的子文档进行排序?

jquery - ASP.NET MVC3 : Adding Textboxes with Jquery and binding to Model

combobox - QML Combobox 报告 ReferenceError : modelData is not defined

css - 禁用将 TfsBuild 中的 NPM 构建步骤结果推送到 SonarQube

node.js - npm install 不适用于 gzipped tarball

c# - MongoDb.Driver IMongoDatabase.GetCollectionNamesAsync() 异常

node.js - mongoose#populate 在数组内的嵌套对象中返回 null

c# - MVC 错误 : The model item passed into the dictionary is null