虚拟填充对文档进行计数的另一种方法是什么?虚拟填充对模型的影响是什么?

时间:2019-05-18 04:04:19

标签: node.js mongodb mongoose-populate

我想计算特定城市的驾驶员总数,所以我正在使用虚拟填充,只想知道它的替代方法以及它对模型的影响?

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

0 个答案:

没有答案