I am new to javascript and mongo and trying to find a course in my MongoDB database collection using id but getting null. Could you please help me with this?
Note: I am using MacBook. This is a very basic thing I am trying to do. I am able to fetch the object using .find() but findByID(id) doesn't seem to work for me. What am I missing? Let me know if any more detail is required.
Edit: A weird observation, refer the image. For the first one, I cannot find it or update it using id but I could find and update the second one. The first one was inserted in database using json file and second one was inserted using .save() in javascript.
PFB my code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercise', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to mongo-exercise database.'))
.catch(err => console.log('Could not connect to mongo-exercise database.', err));
// Create the schema
const schema = new mongoose.Schema({
name: String,
author: String,
price: Number,
tags: [String],
isPublished: Boolean
});
// Call the schema
const Course = mongoose.model('course', schema);
async function updateCourse(id) {
try {
const course = await Course
.findById(id);
console.log('Course is ', course);
}
catch (err) {
console.log('Solution failed: ', err.message);
throw error
}
}
updateCourse("5a68fdf95db93f6477053ddd");
[
]
updateCourse(ObjectId("5a68fdf95db93f6477053ddd"));. findById()takes in a string & internally it does convertstringtoObjectId()prior to querying DB.._id.._idfield in database is of typeObjectId()then use.findById()else if your_idfield is type string in database then use.findOne({_id : someInputString})but you need to remember that type of input should match with type of_idfield in DB. Also do not maintain_idin two different types in DB either maintain it as string orObjectId()for all the docs, I would say to maintain it asObjectId()- let MongoDB create it for docs when they got inserted..