Skip to content
Advertisement

Different types of the field _id of rows after importing data to mongodb and after the creation

I’m trying to write a JS app with MongoDB (I use MongoDB Compass). I have a schema of user:

JavaScript

Then I import some data from JSON file like this:

JavaScript

After the importing the type of field _id is String. But, if I create a user by method create:

JavaScript

the type of _id is ObjectId, therefore, I can’t use methods like User.findByIdAndUpdate, User.findByIdAndRemove etc on the same data, these methods work only with ObjectId type.

Advertisement

Answer

you need to import the _id’s as objectId’s as follow:

JavaScript

or you may use the mongoshell method to generate the objectId from string , node.js example:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement