Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type error in using typescript and mongodb findOneAndUpdate method

This is my mongodb collection model

export class User {
    constructor(
        public _id: ObjectId,
        public username: string,
        public phone: string,
        public password: string,
        public pages: Array<ObjectId>
    ) { }
}

I want to add new ObjectId into pages:

const pageID = new ObjectId()
const result1 = await userCollection.findOneAndUpdate({
    _id: new ObjectId(userID)
    }, {
        $push: {
            pages: pageID
        }
    })

And there is an error near $push

Type '{ pages: ObjectId; }' is not assignable to type 'PushOperator<Document>'.
  Type '{ pages: ObjectId; }' is not assignable to type 'NotAcceptedFields<Document, readonly any[]>'.
    Property 'pages' is incompatible with index signature.
      Type 'ObjectId' is not assignable to type 'undefined'.

I found lots of examples in js and shell, but none in ts. Can anyone help me with that?

like image 855
CHI ZHANG Avatar asked Feb 18 '26 23:02

CHI ZHANG


1 Answers

I encountered the same problem after updating to MongoDB driver v4.9.0. The solution is to cast your update object to Record<string, any>:

const pageID = new ObjectId();
const updateObj: Record<string, any> = {
    pages: pageID
};
const result1 = await userCollection.findOneAndUpdate(
    { _id: new ObjectId(userID) }, 
    { $push: updateObj }
);

The reason is the following PR: 3349, which changed the definition of MatchKeysAndValues, and affected the update argument of the following functions: updateOne, updateMany, findOneAndUpdate, update.

like image 179
Tomasz Kasperczyk Avatar answered Feb 21 '26 13:02

Tomasz Kasperczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!