更新该文档时如何填充参考字段

问题描述

我有 2 个集合用户和预订。我创建了 userSchema 和 bookingSchema 以及预订和用户的路线。

用户架构

const userSchema = new mongoose.Schema({
  name: String,active: {
    type: Boolean,default: true,// select: false,},});

userSchema.pre(/^find/,function (next) {
  this.find({ active: { $ne: false } });
  next();
});


预订架构

const bookingSchema = new mongoose.Schema({
  from: String,to: String,user: {
    type: mongoose.Schema.ObjectId,ref: 'User',});

bookingSchema.pre(/^find/,function (next) {
  this.populate({
    path: 'user ',});

  next();
});

我定义的路线如下

router.get('/api/bookings/:id',async (req,res) => {
  const booking = await Booking.findById(req.params.id);
  res.send(booking);
});

我的问题是我创建了用户文档

 { 
  _id: "60ab239958c0ac2882d30531",active: true,name: "rohit"
 } 

和预订文件

 {
    "_id": "60ab1fe50618d805581f154a","from": "delhi","to": "mumbai","user": {
        "_id": "60ab1fac0618d805581f1549","name": "rohit","__v": 0
    },"__v": 0
}

现在,当我将用户“rohit”中的活动字段更新为 false 时,当我获取 rohit 的预订时,我在用户字段中得到空值! (我无法删除用户架构中的预中间件)

{
    "_id": "60ab1fe50618d805581f154a","user": null,"__v": 0
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)