简体   繁体   中英

Populate in nested schema Mongoose

I have this User model:

  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
        }
      }
    });

And this Experiment model:

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
    }
);

I am trying to populate from User the experiment_id in notification. And from this populate, I would like to populate the author_id as well. I have seen some code like I have done below but I didn't succeed.

I am trying this:

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

  }); 

I fixed it by adding notification.experiment_id in the path

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

  }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM