【问题标题】:mongoose cannot update document with findOneAndUpdate猫鼬无法使用 findOneAndUpdate 更新文档
【发布时间】:2022-01-22 21:13:24
【问题描述】:

考虑这个架构:

const Suspensions = new Schema({
    guildId: {
        type: String,
        ref: 'guilds',
        required: true
    },
    moderatorId: {
        type: String,
        required: true
    },
    userId: {
        type: String,
        required: true
    },
    reason: {
        type: String,
        required: true
    },
    fullFilled: {
        type : Boolean,
        required: false,
    },
    unSuspensionDate: {
        type: String,
        required: true
    },
    roles: [{
        type: String,
        required: true
    }],
    evidence: [{
        type: String,
        required: false
    }],
    caseId: {
        type: String,
        required: true
    }
})

我想将 fullFilled 设置为 true 的更新函数。

export function unSuspend(
    guildId: string,
    userId: string | undefined
): Promise<Suspension>{
    return new Promise<Suspension>(async (resolve, reject) => {
        await Suspend.findOneAndUpdate(
            {guildId: guildId, userId: userId},
            {$set:{fullFilled: true}},
            {new: true},
            (err: any, doc: any) => {
                if(err) reject(err)
                resolve(doc)
            }
        )
    })
}

它会在{$set:{fullFilled: true}} 上引发错误: 'ReadonlyPartial&lt;_UpdateQueryDef&lt;DeepPartial&lt;any&gt;&gt;&gt;'. Property '$set' is incompatible with index signature. Type '{ fullFilled: boolean; }' is not assignable to type 'DeepPartial&lt;any&gt;'. Property 'fullFilled' is incompatible with index signature.

我在用 JS 编写的旧项目中有完全相同的代码,它工作正常。既然我正在使用 TS,是什么导致了这个错误?我也尝试删除 $set:{} 包装器,但这也没有用。

【问题讨论】:

    标签: node.js typescript mongodb mongoose


    【解决方案1】:

    如果您使用 mongoose,则无需在 findOneAndUpdate 查询中写入 $set。您只需更新文档而不使用任何聚合方法。如果您有任何查询,请检查 https://mongoosejs.com/docs/tutorials/findoneandupdate.html mongoose 文档。

    试试这个:

    export function unSuspend(
        guildId: string,
        userId: string | undefined
    ): Promise<Suspension>{
        return new Promise<Suspension>(async (resolve, reject) => {
            await Suspend.findOneAndUpdate(
                {guildId: guildId, userId: userId},
                {fullFilled: true},
                {new: true},
                (err: any, doc: any) => {
                    if(err) reject(err)
                    resolve(doc)
                }
            )
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 2018-07-10
      • 2019-12-16
      • 1970-01-01
      • 2016-05-24
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多