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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With