Reputation: 331
I am learning Node.js. I am stuck in this Mongoose section because of this problem. findById(id) doesn't get my result back and update() doesn't work. I don't know why..
const mongoose = require("mongoose").set("debug", true);
mongoose
.connect("mongodb://localhost/exercise")
.then(() => console.log("Connected Successfully!"))
.catch(err => console.error("Error: ", err.message));
const courseSchema = new mongoose.Schema({
tags: [String],
date: { type: Date, default: Date.now() },
name: String,
author: String,
isPublished: Boolean,
price: Number
});
const Courses = mongoose.model("Course", courseSchema);
async function updateCourse(id) {
const course = await Courses.findById(id);
course.author = "Muhib";
const result = await course.save();
console.log(result);
}
updateCourse("5a68fde3f09ad7646ddec17e");
// console.log(Courses);
I get this error :
TypeError: Cannot set property 'author' of null
btw find() works..
Thanks in advance :)
Upvotes: 1
Views: 426
Reputation: 3441
Try to add try/catch. I'm not sure course..save() work without err
async function updateCourse(id) {
try {
const course = await Courses.findById(id);
course.author = "Muhib";
const result = await course.save();
console.log(result);
} catch (err) {
console.log('err' + err);
}
}
Edit 1: I found a solution a this post
async function updateCourse(id) {
try {
const course = await Courses.findById(id).exec();//fixed at here
course.author = "Muhib";
const result = await course.save();
console.log(result);
} catch (err) {
console.log('err' + err);
}
}
Another solution using findOneAndUpdate
try {
var course = await Courses.findOneAndUpdate(
{"id" : id},
{$set: {"author" : "Muhib"}},
{new : true}
);
res.status(200).json(course);
} catch (error) {
console.log('err' + err);
}
Upvotes: 0
Reputation: 331
I solved the issue..
there is nothing wrong with the code...
first thing first WHY IT DOESN'T WORK
This problem occurs with the imported collections only. Because the imported collection contains _id property as a string
for example {"_id":"5a6900fff467be65019a9001","tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":15,"__v":0}
but what mongoose need is _id wrapped in ObjectId
SOLUTION
when importing json object always make sure that _id is not a string but an object with a $oid as a key and _id as a value
for example
{"_id":"5a6900fff467be65019a9001","tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":15,"__v":0}
should be {"_id":{"$oid":"5c91a66d079f4807847fcde3"},"tags":["angular","frontend"],"date":"2018-01-24T21:56:15.353Z","name":"Angular Course","author":"Mosh","isPublished":true,"price":{"$numberInt":"15"},"__v":{"$numberInt":"0"}}
Upvotes: 2