查询餐厅数据时想获取餐厅提供集合数据。
这是我的数据库模型
餐厅.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: String,
phone: String
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
{ timestamps: true }
);
module.exports = mongoose.model('Restaurant', restaurantSchema);
报价.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RestaurantOffer = new Schema({
offerType: String,
offerDetails: [String],
restaurant: {type: Schema.ObjectId, ref: "Restaurant", required: true}
},
{ timestamps: true }
);
module.exports = mongoose.model('RestaurantOffer', restaurantSchema);
现在我想查询餐厅数据,每家餐厅都会回复另一家与餐厅提供数据一起归档。
let restaurantWithOffer = await Restaurant.find();
res.status(200).json({ success: true, data: restaurantWithOffer });
以上一个为样本。现在我想要下面的回应
{
_id: 5e5976099b8f3737907bcc7e,
name: "Restaurant Name 1",
phone: "0123456789",
offer:{
id: '5e5976099b8f3737907bcc7e',
OfferType: "OfferType",
offerDetails: []
}
},
{
_id: 5e5976099b8f3737907bcc7e,
name: "Restaurant Name 2",
phone: "0123456789",
offer:{
id: '5e5976099b8f3737907bcc7e',
OfferType: "OfferType",
offerDetails: []
}
},
{
_id: 5e5976099b8f3737907bcc7e,
name: "Restaurant Name 3",
phone: "0123456789",
offer:{
id: '5e5976099b8f3737907bcc7e',
OfferType: "OfferType",
offerDetails: []
}
},
First change your offer js with this code .
报价.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantOfferSchema = new Schema({
offerType: String,
offerDetails: [String],
restaurant_id: {type: String, required: true}
},
{ timestamps: true }
);
restaurantOfferSchema.virtual('restaurant', {
ref: 'Restaurant',
localField: 'restaurant_id',
foreignField: '_id',
justOne: true
});
module.exports = mongoose.model('RestaurantOffer', restaurantOfferSchema);
如前所述更改查询
Restaurant.aggregate([
{
$lookup:
{
from: "RestaurantOffer",
localField: "_id",
foreignField: "restaurant",
as: "RestaurantOffer"
}
}
])