【问题标题】:How can I set a document as a DBref in Mongoose and still have access to the document如何在 Mongoose 中将文档设置为 DBref 并且仍然可以访问该文档
【发布时间】:2015-12-23 02:12:31
【问题描述】:

如何使用引用的文档本身设置 DBref,并且仍然可以访问该文档,就好像它已填充在父对象上一样?

如果我有一个将字段设置为 dbref 字段的简单架构:

var PostSchema = new Schema({
  'title': String,
  '_author', { type: Schema.ObjectId, ref: 'users'}
});
var Post = mongoose.model('posts', PostSchema);

var UserSchema = new Schema({
  'name': String
});
Var User = mongoose.model('users', UserSchema);

如果我尝试这样做:

var john = User.findOne({'name': 'john'});
var post = new Post({'title': 'My Post'});
post._author = john;

post.save(function(err) {
  if (!err) {
    console.log(post._author);
  }
});

post._author 属性的值为 author._id。我希望 _author 属性具有整个作者文档的值(类似于我对帖子集合执行查找查询并填充作者对象)。

我唯一的解决方案是在保存回调中执行这样一个 findOne 查询,并确保我将作者重新填充...这感觉有点不对劲,因为当我已经拥有所有信息时基本上不得不重新查询。

有什么建议吗?谢谢

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    这是 Mongoose 的 populate 功能的目的。在您的示例中,您在创建帖子时设置了post._author = john._id,然后在查询帖子集合时,您将使用这样的代码用完整的用户对象填充_author:

    post.findOne({'title': 'My Post'}).populate('_author').exec(function (err, post) {
        // post._author contains a User model instance
    });
    

    【讨论】:

    • 是的,当我只是检索数据时,这非常有效,但是在我设置数据之后,我是否必须像你描述的那样findOne?当我已经拥有所需的数据时,必须发出find 查询似乎有点奇怪。
    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2013-03-28
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多