我想计算特定城市的驾驶员总数,所以我正在使用虚拟填充,只想知道它的替代方法以及它对模型的影响?
const DriverSchema = new Schema({
name: String,
band: String,
cityId : {
type: mongoose.ObjectId,
ref: 'city'
}
});
const CitySchema = new Schema({
name: String
});
CitySchema.virtual('totalMember', {
ref: 'Driver', // The model to use
localField: '_id', // Find people where `localField`
foreignField: 'cityId', // is equal to `foreignField`
count: true // count document
});
const Driver = mongoose.model('driver', DriverSchema);
const City = mongoose.model('city', CitySchema);
City.findOne({})
.populate('totalMember')
.exec((error, city) => {
city.totalMember
});