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

202
Visualizações
How to create an array entry with ObjectId and Number

I am new to mongodb and am trying to make this type of entry:

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            }
        }
    ]
}

Here is my schema code:

const schema = new Schema({
  resources: [
    {
      amount: {
        type: Number,
        required: true,
      },
      resource: {
        _id: {
          type: Schema.Types.ObjectId,
          ref: "Resource"
        }
      }
    }
  ]
});

here is the json code i send

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            }
        }
    ]
}

After processing the request, the following entry is created

{
    "resources": [
        {
            "amount": 1,
            "resource": {
                "_id": "61be82b9549b4ede0c8df07e"
            },
            "_id": "61ebf5d2e47442bd566fe157"
        }
    ],
    "_id": "61ebf5d2e47442bd566fe156",
    "__v": 0
}

Id for the resource was created correctly, but I can't figure out where the resources._id key came from? Where did I make a mistake?

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

0

You have to off _id from schema declaration in the array, after updating schema try inserting new document,

const schema = new Schema({
  resources: [
    {
      _id: false, 
      amount: {
        type: Number,
        required: true,
      },
      resource: {
        _id: {
          type: Schema.Types.ObjectId,
          ref: "Resource"
        }
      }
    }
  ]
});
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