Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65868915/different-types-of-the-field-id-of-rows-after-importing-data-to-mongodb-and-aft

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...