1
const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/mongo-exercise")
.then( ()=> console.log("Connected to MongoDB..."))
.catch(err => console.error("Failed to connect to db...",err));

Below is the course schema and model

const courseSchema = new mongoose.Schema({
    name:String,
    author:String,
    tags:[String],
    date:Date,
    isPublished: Boolean,
    price:Number
});

const Course = mongoose.model('Course',courseSchema);

here is the function to get the list of courses based on certain criteria.

async function getCourses() {
    return await Course
    .find({isPublished:true})
    .or([
        {price : {$gte: 15}},
        {name : /.*by.*/}
        ])
    .sort('-price')
    .select('name author price')
};

here is the function to update the course author of a particular course by its id but its failing and replying course not found

async function updateCourse(id) {
    const mongoose = require('mongoose');
    console.log('checking..');
    if (!mongoose.Types.ObjectId.isValid(id)) {
    console.log('Invalid ID format');
    return;
}
    try {
        const course = await Course.findById(id);
        if (!course) {
            console.log('Course not found');
            return;
        }

        course.isPublished = false;
        course.author = 'Manish';

        const result = await course.save();
        console.log(result);
    } catch (error) {
        console.error('Error updating the course:', error);
    }
}

course id i'm trying to update and similarly other ids that exist in DB but its not working. But when querying the DB the same id appearing.

async function run() {
    const courses = await getCourses();
    console.log("List of courses \n" ,courses);
    
}
updateCourse('5a68fdd7bee8ea64649c2777');

here is the output of the querying DB

List of courses
 [
  {
    _id: new ObjectId('5a68fdd7bee8ea64649c2777'),
    name: 'Node.js Course',
    author: 'Mosh',
    price: 20
  },
  {
    _id: new ObjectId('5a6900fff467be65019a9001'),
    name: 'Angular Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId('5a68fde3f09ad7646ddec17e'),
    name: 'ASP.NET MVC Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId('5a68fe2142ae6a6482c4c9cb'),
    name: 'Node.js Course by Jack',
    author: 'Jack',
    price: 12
  }
]

and here is is the update output

checking..

Connected to MongoDB...

Course not found

I have tried this solution to find the course by its name and its working.

async function testQuery() {
    const course = await Course.findOne({ name: 'React Course' });
    console.log('Course found by name:', course);
}

debugQuery();

what could be the potential reason that it's not updating the course or is there something wrong in my approach?

2 Answers 2

0

The problem is that your schema doesn't have _id: String so mongoose doesn't recognize it and by default thinks _id is an ObjectId not a string.

Just change your schema like this and it should work

const courseSchema = new mongoose.Schema({
  _id: String,
  name: String,
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number
});
Sign up to request clarification or add additional context in comments.

Comments

0

This may be a problem with not awaiting the async function updateCourse.

I put the above code in a single file, but modified the run function to also include and await the updateCourse call, and then explicitly exit, like so:

async function run() {
    const courses = await getCourses();
    console.log("List of courses \n" ,courses);
    await updateCourse('5a68fdd7bee8ea64649c2777');
    process.exit();
}

run();

I inserted the sample documents provided, but set isPublished:true on each. Executing that file produced:

Connected to MongoDB...
List of courses
 [
  {
    _id: new ObjectId("5a68fdd7bee8ea64649c2777"),
    name: 'Node.js Course',
    author: 'Mosh',
    price: 20
  },
  {
    _id: new ObjectId("5a6900fff467be65019a9001"),
    name: 'Angular Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId("5a68fde3f09ad7646ddec17e"),
    name: 'ASP.NET MVC Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId("5a68fe2142ae6a6482c4c9cb"),
    name: 'Node.js Course by Jack',
    author: 'Jack',
    price: 12
  }
]
checking..
{
  tags: [],
  _id: new ObjectId("5a68fdd7bee8ea64649c2777"),
  name: 'Node.js Course',
  author: 'Manish',
  price: 20,
  isPublished: false,
  __v: 1
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.