Reputation: 69
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");
[]
Upvotes: 1
Views: 444
Reputation: 59
Happened to me.when importing using compass, just deselect the _Id property as its a string. When imported mongodb driver will put in a new object _id with and objectid that can be queried.
Upvotes: 1