[英]How to populate data from another collections in mongoose?
我想将 busNumber 从 bus Bus 表填充到 trip 表。 这是公交车 model
const busSchema = new mongoose.Schema(
{
busNumber: {
type: String,
unique: true,
required: true,
},
seats: {
type: Number,
},
},
{
timestamps: true,
}
);
现在我想在行程表中显示公交车编号而不是 bus._id。 我知道如何排除数据但不知道如何包含来自其他 collections 的数据。这是我包含公共汽车 model 的路线 model
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() function 从另一个集合中获取数据 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.