尝试实现CSV导入,以便我使用MonggoseJs在NodeJs中使用批量插入并在此处共享脚本。
说明:
如果我使用' model.save'验证在字符串和电子邮件唯一的最小长度下正常工作,在Schema和Script下面进行批量插入。
// User Schema.
{
"title": {type: String, enum:["Mr", "Ms", "Mrs","Miss","Mstr"]},
"firstName": {
type: String,
trim: true,
required: true,
minlength: 2
},
"lastName": {
type: String,
trim: true,
required: true,
minlength: 2
},
"gender": {type: String, enum: ["Male","Female","Other"]},
"email" : {type: String, unique: true, required: true, trim: true}
}
脚本:将为批量插入执行的承诺
return new Promise((resolve, reject) => {
var bulk = User.collection.initializeOrderedBulkOp();
let _oUserOne =new User({
"title": Mr,
"firstName" : "A",
"lastName" : "S",
"gender" : "Male",
"email" : "xxx@domain.com"
})
let _oUserTwo =new User({
"title": Mr,
"firstName" : "A",
"lastName" : "S",
"gender" : "Male",
"email" : "xxx@domain.com" // Duplicate entry of email
})
bulk.insert(_oUserOne);
bulk.insert(_oUserTwo);
bulk.execute(function (err, r) {
if (err) {
console.error("Error in bulk insert\n", err);
resolve({ result: r, error: err });
}
console.log("OK: Inserted successfully!");
resolve({ result: r, error: null });
});
});