Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

I'm trying to update a document using mongoose, but the update is not happening


I am currently attempting to perform an update operation on a document using Mongoose, a popular MongoDB object modeling library. Unfortunately, despite not encountering any errors within my code, I am facing an issue where the updates are not being reflected in the database. Upon inspecting the documents within the collection, it becomes evident that the values remain unchanged.

const mongoose = require('mongoose');

mongoose.connect("mongodb://127.0.0.1:27017/fruitsDB");

const fruitSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "No name is specified!"]
    },
    rating: {
        type: Number,
        min: 1,
        max: 5,
    },
    review: {
        type: String,
        required: true,
    },
});

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

const getAllFruits = async () => {
    let fruits = await Fruit.find({});
    console.log(fruits);
    mongoose.connection.close();
}

// not working
Fruit.updateOne({_id:"64b82bbf195deb973202b544"}, {name: "Pineapple"});

getAllFruits();

Documents in the fruits collection:-

  {
    _id: ObjectId("64b6c5db10ffbd33c66058f9"),
    name: 'Mango',
    rating: 4,
    review: 'Amazing!',
    __v: 0
  },
  {
    _id: ObjectId("64b6cb255a2732a5a411098d"),
    name: 'Kiwi',
    rating: 5,
    review: 'Best Fruit.',
    __v: 0
  },
  {
    _id: ObjectId("64b6cb255a2732a5a411098e"),
    name: 'Orange',
    rating: 4,
    review: 'Too sour',
    __v: 0
  },
  {
    _id: ObjectId("64b6cb255a2732a5a411098f"),
    name: 'Banana',
    rating: 3,
    review: 'Wierd fruit.',
    __v: 0
  },
  {
    _id: ObjectId("64b6cea306bb054ca06b805d"),
    name: 'Kiwi',
    rating: 5,
    review: 'Best Fruit.',
    __v: 0
  },
  {
    _id: ObjectId("64b6cea306bb054ca06b805e"),
    name: 'Orange',
    rating: 4,
    review: 'Too sour',
    __v: 0
  },
  {
    _id: ObjectId("64b6cea306bb054ca06b805f"),
    name: 'Banana',
    rating: 3,
    review: 'Wierd fruit.',
    __v: 0
  },
// **This is the one I want to update:-**
  {
    _id: ObjectId("64b82bbf195deb973202b544"),
    rating: 5,
    review: "It's a god level fruit.",
    __v: 0
  }

The document should be updated in the database.


Solution

  • Fruit.updateOne() and getAllFruits() are asynchronous functions, you need to make sure the execution order is correct. Update first, then query the data.

    const getAllFruits = async () => {
        let fruits = await Fruit.find({});
        console.log(fruits);
        mongoose.connection.close();
    }
    
    const run = async () => {
      await Fruit.updateOne({_id:"64b82bbf195deb973202b544"}, {name: "Pineapple"});
      getAllFruits();
    }
    
    run();