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.)