如何填充猫鼬中的嵌套对象?

How to populate the nested objects in mongoose?

这是预订架构

const bookingSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  routeId:{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Route",
    required: true,
  }
})

在此 table 中,routeId(路线模式)包含总线 table(已引用)。

const routeSchema = new mongoose.Schema({
  location:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Location',
    required: true
  },
  duration: {
    type: Number,
    required: true
  },
  Bus:{
    type: mongoose.Schema.Types.ObjectId,
    ref:"Bus",
    required: true
  },
  date: {
    type:String,
    required: true
  },
},
{
  timestamps: true,
});

最后是巴士模型

const busSchema = new mongoose.Schema(
  {
    busNumber: {
      type: String,
      unique: true,
      required: true,
    },
    seats: {
      type: Number,
    },
  },
  {
    timestamps: true,
  }
);

现在我只想显示公交车号码而不是整个公交车数据。这是我得到的回应。 https://i.stack.imgur.com/S1qyZ.png

这是我应用的查询。

router.get("/bus/myBooking/one/:id", auth, async (req, res) => {
  const _id = req.params.id;
  const myBooking = await Booking.findById({ _id })
    .populate({path: 'routeId', populate: 'Bus'})
    .select(["-_id","-userId","-createdAt","-updatedAt","-__v","-passengers._id","-departureDetails._id","-arrivalDetails._id"]);
  try {
    return !myBooking
      ? res.status(404).send("No booking found")
      : res.status(200).send(myBooking);
  } catch (e) {
    res.status(500).send();
  }
});

此方法适用于某些版本的 mongoose,所以您可以试试这个:

 await Booking.findById({ _id })
  .populate({ 
   path: 'routeId',
      populate: {
         path: 'Bus',
         model: Bus,
         select:"-_id busNumber"
   } 
 })