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

221
Visualizações
Adding a new key in mogoDB collection using mongoose

Take a scenario where my current collection named fruits looks like:

{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8}

Now, if I intend to add a new key-value pair (key named quantity) only in the second doc (i.e., where name: Banana), I would do the following in the terminal using mongoDB:

db.fruits.updateOne({name : "Banana"},{$set:{quantity : 20}})

and now my collection would look like the following:

{"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7}
{"_id" : ObjectId("abc...."), "name" : "Banana", "rating" : 9}
{"_id" : ObjectId("lmn...."), "name" : "Kiwi", "rating" : 8, "quantity" : 20}

So how do I achieve the same thing using mongoose in my app.js. I don't want to change the entire schema for all the docs, becoz mongoDB is a NOSQL and a structure should not be cumpulsory.

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

0

You should define a schema corresponding to the collection, let's call it fruit.model.js:

const mongoose = require('mongoose');

const fruitSchema = new mongoose.Schema({
    name: String,
    quantity: Number
});

const Fruit = mongoose.model('Fruit', fruitSchema);

module.exports = Fruit;

And the use it to run your query using the findOneAndUpdate method:

const mongoose = require('mongoose');
const Fruit = require('./fruit.model');

const updateFruit = async () => {
    await Fruit.findOneAndUpdate({ name: "Banana" }, { quantity: 20})
}
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