【问题标题】:Moongose schema type not working in aggregate猫鼬模式类型不能聚合
【发布时间】:2021-03-26 20:52:57
【问题描述】:

我有架构

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

【问题讨论】:

    标签: mongodb mongoose aggregation-framework mongoose-schema


    【解决方案1】:

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

    这是预期的:

    Mongoose 不投射聚合管道。那是因为 聚合管道可以并且通常会改变 MongoDB 中的数据。如果需要强制转换,可以使用 find(),也可以 使用 Query#cast() 方法来转换过滤器:

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

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2013-09-22
      • 2021-09-25
      • 1970-01-01
      • 2015-05-19
      • 2018-06-21
      • 2015-07-27
      • 2013-06-24
      • 2019-08-29
      相关资源
      最近更新 更多