I want to push a message in an array with Mongoose/Mongo. Typescript claims that:
No overload matches this call. Overload 1 of 3, '(id: any, update: UpdateQuery, options: QueryOptions & { rawResult: true; }, callback?: ((err: any, doc: FindAndModifyWriteOpResultObject, res: any) => void) | undefined): any', gave the following error. Type '{ messages: { message: string; authorId: string; }; }' is not assignable to type 'PushOperator<_AllowStringsForIds<Pick<Pick<_LeanDocument, string | number | symbol>, string | number | symbol>>>'. Type '{ messages: { message: string; authorId: string; }; }' is not assignable to type 'NotAcceptedFields<_AllowStringsForIds<Pick<Pick<_LeanDocument, string | number | symbol>, string | number | symbol>>, readonly any[]>'. Property 'messages' is incompatible with index signature.
Here is the code snippet:
const conversation = await Conversation.findByIdAndUpdate(
conversationId,
{
$push: { messages: { message, authorId } },
lastMessage: {
authorId,
snippet: `${message.substring(0, 47)}...`,
read: false,
},
},
{ new: true }
);
The build crash because of this. How to fix it?
This is an issue with types not lining up.
My understanding is the push operation can only be done on a field that is explicitly defined as an array at some point in your code previously.
A potential solution is to explicitly set the type of your collection to contain the fields you want (which is good practice anyway).
So rather than something along the lines of
const Conversations = database.collection('conversations');
You would explicitly define the schema for the 'conversation' documents, and then type the collection:
import { Collection } from 'mongodb';
//...
type Conversation = {
messages: { message: String, authorId: Number }[],
//...
}
const Conversations: Collection<Conversation> = database.collection('conversations');
If you know you're doing the right thing, then you can bypass this with as.
The following example illustrates this.
await driver.collection('myCollection').findOneAndUpdate(
{
_id: "<some _id that I have>",
},
{
'$push': {
'myArrayField': {
'$position': 0,
'$each': [ myItemToPush ],
}
} as unknown as PushOperator<Document>,
},
{
returnDocument: 'after',
upsert: false,
},
);
Note the as unknown as PushOperator<Document> - this is what's going to get you out of this problem. Use it properly as Tyscript will allow you to use as anywhree and used unabated, this can defeat the purpose of using a type system.