填充嵌套模式猫鼬

时间:2018-07-01 17:34:44

标签: javascript mongodb 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
    }
);

我正在尝试从用户填充通知中的experiment_id。 从这个填充中,我也想填充author_id。 我看到了一些代码,就像我在下面所做的一样,但是没有成功。

我正在尝试:

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

  }); 

1 个答案:

答案 0 :(得分:0)

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

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

  });