如何从猫鼬中的另一个集合填充数据?

How to populate data from another collections in mongoose?

我想填充从公交车 table 到行程 table 的 busNumber。 这是巴士模型

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

现在我想在行程中显示公交车号码 table 而不是 bus._id。我知道如何排除数据但不知道如何包含其他集合中的数据。 这是我包含公交车模型的路线模型

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

这里是查询:

router.get("/trips", async (req, res) => {
  if ((!req.query.departure && !req.query.arrival) || !req.query.date) {
    return res.send({
      error: "Please enter the data to get the trip",
    });
  }
  const { departure, arrival, date } = req.query;

  const locations = await Location.find({
    "departureLocation.name": departure,
    "arrivalLocation.name": arrival,
  });

  const ids = locations.map(location => location._id);
  const routes = await Route.find({
    $and: [{ location: { $in: ids } }, { date }],
  }).select(['-busId', '-location', '-_id', '-createdAt', '-updatedAt', '-__v']);

  return !routes ? res.status(404).send() : res.status(200).send(routes);
});

这是我得到的结果 https://i.stack.imgur.com/AwK5N.png

如何使用 populate() 函数从 mongoose 中的另一个集合中获取数据

使用此代码作为您的填充总线密钥

 router.get("/trips", async (req, res) => {
      if ((!req.query.departure && !req.query.arrival) || !req.query.date) {
        return res.send({
          error: "Please enter the data to get the trip",
        });
      }
      const { departure, arrival, date } = req.query;
    
      const locations = await Location.find({
        "departureLocation.name": departure,
        "arrivalLocation.name": arrival,
      });
    
      const ids = locations.map(location => location._id);
      const routes = await Route.find({
        $and: [{ location: { $in: ids } }, { date }],
      }).populate("Bus").select(['-busId', '-location', '-_id', '-createdAt', '-updatedAt', '-__v']);
    
      return !routes ? res.status(404).send() : res.status(200).send(routes);
    });