【问题标题】:Reference from multiple mongoose schemas using .populate()使用 .populate() 从多个猫鼬模式中引用
【发布时间】:2023-04-09 11:49:01
【问题描述】:
const blogPostSchema = new mongoose.Schema({
  postedBy: {
    type: ObjectId,
    ref: 'User',
    ref: 'Employer',
},  

});

  BlogPost.findById(id)
    .populate("postedBy", "_id fName lName")
    .exec();

我有三种模式用户、雇主和博文

我正在尝试从用户模型或雇主.populate("postedBy", "_id fName lName"),具体取决于发布博客的人。

我如何从两个模式中引用这可能吗?

【问题讨论】:

    标签: reactjs mongodb mongoose


    【解决方案1】:

    你可以在同一个 find() 中链接多个 .populate()

    BlogPost.findOne().populate().populate().populate().exec((err, post) => {
            if (err) { console.error(err);
                       return res.status(500).json({ error: err }) }
            res.json(post);
        })
    

    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2020-11-19
      • 2020-07-18
      • 2019-04-12
      • 1970-01-01
      相关资源
      最近更新 更多