猫鼬用嵌套的对象数组填充对象

时间:2019-09-22 14:11:39

标签: mongoose

就像标题一样,我想用嵌套的对象数组填充一个对象。

我尝试了简单的populate()以及在StackOverflow上找到的几种解决方案。关于这个,我在下面引用。

我的路线

router.get('/users/:user/notifications', (req, res) => {
  User.findById(req.user._id)
    .populate({
      path: 'notifications',
      populate: {
        path: 'userFollowedNot',
        model: 'User',
      },
    })
    .populate({
      path: 'notifications',
      populate: {
        path: 'newShortsNot',
        model: 'Shortcut',
      },
    })
    .exec()
    .then((user) => {
      res.render('notifications', { user, csrfToken: req.csrfToken() })
    })
});

我的模特

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    lowercase: true,
    unique: true,
    required: true,
  },
  password: {
    type: String,
  },
  showNsfw: {
    type: Boolean,
    default: true,
  },
  timezone: {
    type: String,
    default: 'CEST',
  },
  notifications: {
    userFollowedNot: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    }],
    newShortsNot: [{
      type: String,
      ref: 'Shortcut',
    }],
  },
});

0 个答案:

没有答案