I’m trying to write a JS app with MongoDB (I use MongoDB Compass). I have a schema of user:
JavaScript
x
17
17
1
const mongoose = require('mongoose');
2
3
const userSchema = new mongoose.Schema({
4
name: {
5
type: String,
6
minlength: 2,
7
maxlength: 30,
8
required: true,
9
},
10
about: {
11
type: String,
12
minlength: 2,
13
maxlength: 30,
14
required: true,
15
}
16
});
17
Then I import some data from JSON file like this:
JavaScript
1
8
1
[
2
{
3
"name": "Ada Lovelace",
4
"about": "Mathematician, writer",
5
"_id": "dbfe53c3c4d568240378b0c6"
6
}
7
]
8
After the importing the type of field _id is String. But, if I create a user by method create:
JavaScript
1
12
12
1
const createUser = (req, res) => {
2
const { name, about } = req.body;
3
User.create({ name, about })
4
.then((user) => res.status(200).send({ data: user }))
5
.catch((err) => {
6
if (err.name === 'ValidationError') {
7
return res.status(400).send({ message: `Wrong value: ${err}` });
8
}
9
return res.status(500).send({ message: `Server error: ${err}` });
10
});
11
};
12
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
1
8
1
[
2
{
3
"name": "Ada Lovelace",
4
"about": "Mathematician, writer",
5
"_id": { "$oid":"dbfe53c3c4d568240378b0c6"}
6
}
7
]
8
or you may use the mongoshell method to generate the objectId from string , node.js example:
JavaScript
1
16
16
1
var MongoClient = require('mongodb').MongoClient;
2
var ObjectID = require('mongodb').ObjectID;
3
var url = "mongodb://localhost:27017/test";
4
var file = require('./myfile.json');
5
MongoClient.connect(url, {useNewUrlParser: true }, function(err, db) {
6
var dbo = db.db(" test");
7
file.map(elem => {
8
elem._id = ObjectID(elem._id)
9
dbo.collection("example").insertOne(elem, function(err, res) {
10
if (err) throw err;
11
});
12
})
13
console.log("done")
14
db.close();
15
});
16