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:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    minlength: 2,
    maxlength: 30,
    required: true,
  },
  about: {
    type: String,
    minlength: 2,
    maxlength: 30,
    required: true,
  }
});

Then I import some data from JSON file like this:

[
  {
      "name": "Ada Lovelace",
      "about": "Mathematician, writer",
      "_id": "dbfe53c3c4d568240378b0c6"
  }
]

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

const createUser = (req, res) => {
  const { name, about } = req.body;
  User.create({ name, about })
    .then((user) => res.status(200).send({ data: user }))
    .catch((err) => {
      if (err.name === 'ValidationError') {
        return res.status(400).send({ message: `Wrong value: ${err}` });
      }
      return res.status(500).send({ message: `Server error: ${err}` });
    });
};

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:

 [
   {
       "name": "Ada Lovelace",
       "about": "Mathematician, writer",
       "_id": { "$oid":"dbfe53c3c4d568240378b0c6"}
   }
 ]

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

 var MongoClient = require('mongodb').MongoClient;
 var ObjectID = require('mongodb').ObjectID;
 var url = "mongodb://localhost:27017/test"; 
 var file = require('./myfile.json');
 MongoClient.connect(url, {useNewUrlParser: true }, function(err, db) {
     var dbo = db.db(" test"); 
     file.map(elem => {
         elem._id = ObjectID(elem._id)
         dbo.collection("example").insertOne(elem, function(err, res) { 
             if (err) throw err;
         });
     })
     console.log("done")
     db.close();
 });
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement