I'm getting a TS2322 error when using `$push` with `updateOne`

My code is as follows:

async function reply(collection: Collection, body: MyBody) {
    const {reply} = body
    if (!reply) return
    await collection.findOneAndUpdate({
        _id: new ObjectId(reply)
    }, {
        $inc: { subCount: 1},
        $push: { children: reply }
    })
}

But the compiler throws an error when I try to compile it to JS:

TS2322: Type  { children: string; }  is not assignable to type  PushOperator<Document> 
Type  { children: string; }  is not assignable to type  NotAcceptedFields<Document, readonly any[]> 
Property  children  is incompatible with index signature.
Type  string  is not assignable to type  undefined 
mongodb.d.ts(6361, 5): The expected type comes from property  $push  which is declared here on type  UpdateFilter<Document>

The compiler says my $push is written incorrectly, but I don’t seem to be doing anything differently than the example in the documentation.

The dependency I’m using is nodejs mongodb@2.8.1.

1 Like

I am not 100% certain, but I think the wrong element is being pushed into the push operator. I think the ObejectId(reply) is being passing in the wrong value to push operator.

It would be better if you could provide some more detail or a link to your full code. Cause I can’t determine what MyBody is here…

The code itself should be fine, because if I use // @ts-ignore to block this compile error, the runtime does not report an error and I get the results I expect.

Also if I change findOneAndUpdate to updateOne in the code I gave above, the compile error goes away, but if I change it to updateMany the error reappears.

I’ll add one more detail, reply is a string of length 24 storing hexadecimal numbers.

Now, the error no longer exists when I use updateOne, but it still exists when I replace updateOne with other actions that have an update attached to them (e.g., findOneAndUpdate updateMany, etc.), and I have to use // @ts-ignore to block the error.