I am on the UPDATE a document - Query first and Update first Topic under CRUD operations using Mongoose.
AS pass the query first to update a document in the database, it just says Connected to MongoDB… and doesn’t update anything, I waited for a long time as well but still the same.
Then when I did the 2nd approach where you have to update it directly without retrieving the document, I get a result:
{ n:0, Modified: 0, ok: 1 }
The error is because we were importing JSON file which has “_id” as a String and not an ObjectId, you can do these steps (i have found this on StackOverflow and copied everything , sorry I don’t have the link rn )
In the first place:
Check your MongoDB database, if _id is stored as String, findById(id) can not find since it identifies ObjectId. If you’ve used import database by using mongoimport command and including _id in JSON:
Solution 1:
modify your JSON and for each document, change _id for instance:
_id: “5a68fde3f09ad7646ddec17e” to the following and run mongoimport again:
"_id": { "$oid": "5a68fde3f09ad7646ddec17e" }
Solution 2:
delete _id in the JSON file, drop collection, and import again. Mongo will auto-create _id.
After any of solutions above, findById(“id”) will work.
Secondly:
Specifically in such cases where your _id elements are string, might be a better idea to use MongoDB package: npm I MongoDB
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db(“your_db_name”);
dbo.collection(“fruits_collection”)
.find({_id:‘5a1cf77920701c1f0aafb85e’})
//.find({_id:‘5a1cf77920701c1f0aafb85e’}, { projection: { _id: 0, name: 1, color: 1} }) // to select specific columns desired
.toArray(function (err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The above simple code, assumed you manage error handling yourself, either through try-catch, or sending 404 as status code, or redirect to the error page template, depending on whether the code is embedded in the Express route handler or not.
For me, the first solution solved everything
Hope this helped …
ayeshazahid is right. a simple solution is to just delete the ids from the json array before importing to let mongo generate ids for each document. if you don’t, the ids will be strings which is wrong. you shouldn’t import ids in the first place.