首页 > 解决方案 > 填充嵌套模式 Mongoose

问题描述

我有这个用户模型:

  const userSchema = new Schema({
      _id: {
        type: Schema.Types.ObjectId,
        required: true
      },
      name: {
        type: String,
        required: true
      },
      email: {
        type: String,
        unique: true,
        required: true
      },
      notification: {
        experiment_id: {
          type: Schema.Types.ObjectId,
          ref: "Experiment",
          required: false
        },
        seen: {
          type: Boolean,
          required: true,
          default: false
        }
      }
    });

而这个实验模型:

const experimentSchema = new Schema(
  {
    _id: {
      type: Schema.Types.ObjectId,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    description: {
      type: String,
      required: true,
      default: "No Description"
    },
    author_id: {
      type: Schema.Types.ObjectId,
      ref: "User",
      required: true
    }
);

我正在尝试从用户填充通知中的实验 ID。从这个填充中,我也想填充 author_id。我已经看到了一些类似我在下面所做的代码,但我没有成功。

我正在尝试这个:

User.find(
  {
    _id: req.params.currentUserId
  },
  "notification"
)
  .populate({ path: "experiment_id", populate: { path: "author_id" } })
  .exec((err, notif) => {

  }); 

标签: javascriptmongodbmongoose

解决方案


我通过在路径中添加notification.experiment_id来修复它

User.find(
  {
    _id: req.params.currentUserId
  },
  "notification"
)
  .populate({ path: "notification.experiment_id", populate: { path: "author_id" } })
  .exec((err, notif) => {

  }); 

推荐阅读