猫鼬模式类型不能聚合

Moongose schema type not working in aggregate

我有架构

const UserSchema = new Schema({
    _id: {
      type: String,
      require: true
    },
    paused: {
      type: Boolean,
      default: false
    },
    name: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      enum: ['private', 'group']
    },
})

const PasswordSchema = new Schema({
    password: {
      type: String,
      require: true
    },
    used: {
      type: Boolean,
      default: false,
    },
    usedBy: UserSchema
})

像这样,效果很好

await Password.findOne({"usedBy._id": 123}) // 123 is converted to string

但是聚合没有转换 _id

await Password.aggregate().match({ "usedBy._id": 123 }) // 123 keeps number, so the query returns null

这正常吗?我不想在所有查询中手动转换 _id

根据问题:https://github.com/Automattic/mongoose/issues/10032

这是预期的:

Mongoose doesn't cast aggregation pipelines. That's because aggregation pipelines can, and usually do, change the shape of the data in MongoDB. If you need casting, you can use find(), or you can use the Query#cast() method to cast the filter:

await Password.aggregate().match(new Query({ "usedBy._id": 123 }).cast(Password).getFilter())