1

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");

[enter image description here]

7
  • 1
    MongoDB _id fields are usually type ObjectId, not string. Try updateCourse(ObjectId("5a68fdf95db93f6477053ddd")); Commented May 18, 2020 at 23:52
  • 3
    @Joe : . findById() takes in a string & internally it does convert string to ObjectId() prior to querying DB.. Commented May 18, 2020 at 23:58
  • 1
    That is good to know! So I've been wasting the effort to convert all this time. Commented May 19, 2020 at 0:01
  • 1
    @Joe : Yes, it's a wrapper func provided by mongoose, useful when you're querying only with _id.. Commented May 19, 2020 at 0:03
  • 1
    @Vers : If your _id field in database is of type ObjectId() then use .findById() else if your _id field is type string in database then use .findOne({_id : someInputString}) but you need to remember that type of input should match with type of _id field in DB. Also do not maintain _id in two different types in DB either maintain it as string or ObjectId() for all the docs, I would say to maintain it as ObjectId() - let MongoDB create it for docs when they got inserted.. Commented May 19, 2020 at 4:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for pointing that out. What you suggested was correct but it still doesn't let me find by id :(

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.