I am trying to update a collection using async/await. Below is my code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mongo-exercises')
.then(() => {
console.log('Connected to MongoDB');
UpdateCourse("5a68fdd7bee8ea64649c2777");
})
.catch(error => console.error('Could not connect to MongoDB : ' + error));
const courseSchema = mongoose.Schema({
name: String,
author: String,
tags: [String],
date: Date,
isPublished: Boolean,
price: Number
});
const Course = mongoose.model('course', courseSchema);
async function UpdateCourse(id) {
console.log(`Inside Update Course. Finding ${id}`);
const course = await Course.findById(id);
console.log(`Course: ${course}`);
if(!course)
return;
course.isPublished = true;
course.author = 'Another Author';
//course.set({isPublished: true, author: 'Another Author'});
const saved = await course.save();
console.log(saved);
}
I query the collection in mongo shell which produces the below output:
In the UpdateCourse() method I am getting null as value for course. I do have the id in the collection. Could anybody tell me why I am getting this error while using async/await.
I tried changing findById() -> findOne({_id: id})
. Same error. I tried changing findById() -> find({_id: id})
here I am getting UnhandledPromiseRejectionWarning: Unhandled promise rejection.
. Not understanding why.