Home > OS >  Adding a new key in mogoDB collection using mongoose
Adding a new key in mogoDB collection using mongoose

Time:12-23

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.

CodePudding user response:

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})
}
  • Related