Mongoose findById() is returning null?

Tell us what’s happening:
Describe your issue in detail here.
Please help. findByID(line 120) is not returning the doc in the callback. I don’t understand why. Another strange thing is when i ‘show collections’ there are 2 collections with the names firstmodels and Firstmodel showing in mongo shell. Please reply. I can explain more.

here is the glitch link
https://glitch.com/edit/#!/modern-few-truck

Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36.

Challenge: Exercise Tracker

Link to the challenge:

It would be easier to help if we could see your code.

Oh im sorry. Added the live site link by mistake. Corrected it now

A few things that I noticed in your post route:

const newM = new Firstmodel({
    _id: String,
    username: req.body.username,
    description: "",
    duration: 0,
    date: d
  });

When you create a new document, you usually don’t set the _id yourself, Mongoose does that for you. It’s also not of type String but it’s an ObjectId. I have no clue what happens if you tell Mongoose to save a field _id with type String, maybe Mongoose just ignores it because _id is a reserved field name, but it could also be the reason why you get null back when you try to find the record by id.

Another possibility:

If you define a model like this:
const Firstmodel = mongoose.model("Firstmodel", firstSchema);
Mongoose will take the name of your Model (“Firstmodel”) and a) pluralise it and b) make it lowercase, that’s why you end up with a collection “firstmodels”. On the other hand, you explicitly set the collection name to “Firstmodel” in your Schema definition, which I think overrides the other name. So you’re saving to one collection, but trying to read from a different one.

I’d definitely recommend to check the actual content of the database, either with the Shell if you’re comfortable with it, or with an easier tool like MongoDB Atlas.


Last comment… you’re calling findByIdAndUpdate(req.params._id); in line 118 , and right after that,
Firstmodel.findById(req.params._id, function(err, data) {...}

The first function call takes a while to complete. The database might not be updated yet when you try to .findById the document.

(By the way It’s a bit confusing to give your function the same name as the Mongoose method on the Model prototype, but that shouldn’t cause issues, just something I’d do differently.)

Thanks for replying. As you said I checked the collections in mongo shell. I found this strange thing that ‘db.Firstmodel.find()’ doesn’t give any output but ‘db.firstmodels.find()’ contains all docs I created earlier. So what should i do now?
why is no document getting created/saved in ‘Firstmodel’ collection?? Why is it empty?

Whatever record you save will go into collection “firstmodels”, because Mongoose pluralises the name of the Model and then puts it to lowercase.

But when you call Firstmodel.findById(...), it’ll refer to this:

const firstSchema = new Schema(
  {
    username: { type: String, required: true, unique: true },
    description: String,
    duration: Number,
    date: { type: Date, default: Date.now() }
  },
  { collection: "Firstmodel" }
);

const Firstmodel = mongoose.model("Firstmodel", firstSchema);

So it’ll search in a collection called “Firstmodel”, which is empty. What happens if you remove { collection: "Firstmodel" } from the Schema?

I removed { collection: "Firstmodel" } and tried again that but no luck. I even created a new user but it saved to ‘firstmodels’ instead of ‘Firstmodel’ so Firstmodel is still empty.

That was to be expected. Everything now goes into collection firstmodels. You should be able to retrieve data from that collection, however there’s still some async issues with your function calls. By the time you res.json(savedData), the findByIdAndUpdate and findById functions haven’t returned any data yet.

The solution would be to put the findById function call inside the findByIdAndUpdate callback, and then to res.json from within the findById callback. In principle, like this:

const findByIdAndUpdate = function(id) {

    Firstmodel.findByIdAndUpdate( id, {newData}, function(err, data) {

        if (err) {
          console.log(err);
        } else {
            // now proceed to next function
            findById(id)
        }
      }
    );
  };
  
const findById = function(id) {
  Firstmodel.findById(req.params._id, [projection], function(err, data) {
    if (err) {
      console.error(err);
    } else {
      // now return data
      res.json(data);
    }
  })};

  findByIdAndUpdate(req.params._id); //call
  

okay so I did 2 things

  1. ) I just had to remove the empty collection ‘Firstmodel’ so all records get saved in the right collection(since there is only one collection left) in the db so updating and finding is working properly as I wanted.
  2. )I just noticed the async issue you told me so I did the change as you said so even that is fixed now.

Overall, Everything is working right now. Thanks a lot man!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.