【问题标题】:findById in mongoose returns null for a certain schemamongoose 中的 findById 为某个模式返回 null
【发布时间】:2020-09-09 15:35:58
【问题描述】:

我有一个名为 subcategory 的架构:

const subCategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: false
    },
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: true
    },
    image: {
        type: String,
        required: false
    }
})

但是在执行此操作时:const subCategoryRecord = await this.subCategoryModel.findById("idAsString") 我得到 null

我读到了其他问题,例如this (这里说我应该发送new ObjectId('id')而不是string

但我有另一个名为category 的架构,在通过发送字符串执行findById 时,我确实得到了结果,有什么区别?

这就是类别架构:

const categorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: false
    },
    image: {
        type: String,
        required: false
    }
})

这个作品:const category = await this.categoryModel.findById('categoryIdAsString')

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    由于您没有在Schema 中指定_id 字段,因此它将是ObjectId 类型。对于findById,您可以将id 作为String 传递,Mongoose 会将其转换为ObjectId 以进行查询。

    由于您收到null 响应(没有转换错误),我认为您将有效的ObjectId 字符串传递给查询,并且可能没有任何记录与提供的id 匹配

    您可以使用以下方法检查您是否传递了有效的id

    mongoose.isValidObjectId(idAsString)
    

    【讨论】:

      【解决方案2】:

      _id 是一个对象,即使在使用“type of”测试时它会说它是一个字符串。 就我而言,这在模型中有效:

      authorId: { type: mongoose.Schema.Types.ObjectId, ref: "users" }
      

      此外,如果您需要将 _id 与保存为字符串的 id 进行比较,您可以使用 .equals() 来返回布尔值:

      user.userId.equals(checkUser._id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-24
        • 2014-10-29
        • 2019-07-15
        • 2019-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多