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

374
Visualizações
When Im trying to push an _id into an array of ObjectId Typescript throws an error

This is the code :

async function create(data: any) {
    try {
        //Creates and order
        let createdOrder = await model.create(data);

        //Push into bike orders array the id of the newly created order
        let bike = await bikeModel.findById(createdOrder._id);

        bike?.orders.push(createdOrder._id);
    } catch (error: any) {
        console.log(`[${RESOURCE}:create] controller error:${error}`);
        throw error;
    }
}

This is the error I get:

Argument of type 'ObjectId' is not assignable to parameter of type '{ type: typeof mongoose.Types.ObjectId; ref: "Order"; }'.
  Type 'ObjectId' is missing the following properties from type '{ type: typeof ObjectId; ref: "Order"; }': type, refts(2345)

And this is my model :

const bikeSchema = new mongoose.Schema({
name: String,
model: String,
color: String,
location: String,
rating: String,
available: String,
orders: [
    {
        type: mongoose.Types.ObjectId,
        ref: 'Order',
    },
],

});

I tried almost everything but it doesnt seem to let me do anything

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is that you are trying to push a single value onto an array of objects the correct. If look at your schema you will notice that your orders attribute is of type:

{ type: mongoose.Types.ObjectId, ref: 'Order' }[]

Hence what your code should look as follows:

async function create(data: any) {
    try {
        //Creates and order
        let createdOrder = await model.create(data);

        //Push into bike orders array the id of the newly created order
        let bike = await bikeModel.findById(createdOrder._id);

        bike?.orders.push({type: createdOrder._id, ref: 'order'});
    } catch (error: any) {
        console.log(`[${RESOURCE}:create] controller error:${error}`);
        throw error;
    }
    
}
about 4 years ago · Juan Pablo Isaza 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