Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

542
Visualizações
Mongo $push operator do not accept object according to typescript: "No overload matches this call"

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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');
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda