数据导入mongodb后和创建后的行字段_id的不同类型



我试图用MongoDB写一个JS应用程序(我使用MongoDB指南针)。我有一个用户模式:

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

然后我从JSON文件中导入一些数据,像这样:

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

导入后,字段_id的类型为String。但是,如果我通过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}` });
});
};

_id的类型是ObjectId,因此,我不能在相同的数据上使用User.findByIdAndUpdate,User.findByIdAndRemove等方法,这些方法只适用于ObjectId类型。

您需要将_id's导入为objectId's,如下所示:

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

或者您可以使用mongoshell方法从字符串生成objectId, node.js示例:

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

最新更新