Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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})
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda