【问题标题】:Mongoose Model.find -> Edit -> Callback?Mongoose Model.find -> 编辑 -> 回调?
【发布时间】:2016-06-20 09:36:10
【问题描述】:

抱歉标题含糊不清,但我想做的是以下内容: 我有 2 个猫鼬模型:帖子和用户(可以是帖子的作者)

const Post = new Schema({
    title: {type: String, required: true, unique: true},
    content: {type: String, required: true},
    date_created: {type: Date, required: true, default: Date.now},
    authorId: {type: String, required: true},             // ObjectId
    author: {type: Schema.Types.Mixed},
    page: {type: Boolean, required: true, default: false}
});

post.find()
mongoose 向 MongoDB 发送查询
MongoDB 返回文档
基于 @987654323 检索作者的中间件@property
将找到的用户添加到帖子author 字段
post.find callback

这可能吗?

【问题讨论】:

    标签: node.js mongodb mongoose middleware


    【解决方案1】:

    是的,mongoose document references and population 会为你做这件事。

    const Post = new Schema({
        // ...
        author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"}
    });
    

    ref: "User" 告诉 Mongoose 使用“用户”类型作为对象类型。确保你有一个用 Mongoose 定义的“用户”模型,否则这将失败。

    要加载完整的对象图,请使用查询的populate 方法:

    
    Post
      .findOne(/* ... */)
      .populate('author')
      .exec(function (err, story) {
        // ...
    
      });
    

    附:我在 my MongooseJS Fundamentals 截屏包中介绍了这个以及更多内容。

    【讨论】:

    • 谢谢!这确实成功了! ^^ 代码现在可以工作了 :) const body = yield this.Model.find() .populate('authorId') .lean();
    猜你喜欢
    • 2016-06-28
    • 2021-10-22
    • 2018-03-20
    • 2015-02-07
    • 2019-12-26
    • 1970-01-01
    • 2012-01-19
    • 2017-01-13
    • 2020-08-11
    相关资源
    最近更新 更多