【问题标题】:bulk.insert(doc) default value not able to inserted MongoDB nodejsbulk.insert(doc) 默认值无法插入 MongoDB nodejs
【发布时间】:2021-07-31 15:35:41
【问题描述】:

我已插入 100k 条记录,已成功批量上传记录。但是,如果我使用bulk.insert(doc),则默认值不会使用 mongoose 和 Nodejs 插入。像 createdAtupdatedAt 字段作为默认值未插入。我试图添加选项 setDefaultsOnInsert: true bulk.insert 没有添加值的选项。目前,我添加了我的代码。请帮助我提前。

代码

let data = req.body;
    var bulk = callDispositionModel.collection.initializeOrderedBulkOp();
    var counter=0
    data.forEach(doc1 => {
        bulk.insert(doc1);
        if (counter % 5000 == 0) {
            bulk.execute();
            bulk = callDispositionModel.collection.initializeUnorderedBulkOp();
            counter = 0;
        }

    counter++
    })

    if (counter > 0) {
        bulk.execute(function(err,result) {
        if(err){
            console.log(`err `, err)
        }else{
            console.log(`result `, result)
            return res.send({success: true, message:'data uploaded successfully')
        }
        });
    }

架构或模型

let dispositionSchema = new mongoose.Schema({
    name : {type: String, default: null},
   mobile : {type : String, default: null},
    remarks : {type: String, default:null},
    duration: {type : String, default: null},
    amount : {type : Number, default: 0},
    date : {type : String, default: null},
    time : {type : String, default: null},
    createdAt: {type: Date, default: Date.now },
    updatedAt: {type: Date, default: Date.now }
});

const disposition = mongoose.model('disposition', dispositionSchema);
export default disposition;

数据

在mongodb中插入数据

{
    "_id" : ObjectId("6098e6d007e2804b9c1f8317"),
   "name" : "senthil",
    "amount" : 0
}
{
    "_id" : ObjectId("6098e6d007e2804b9c1f8316"),
    "name" : "periyas",
    "amount" : 0
}
  

但是,我已经预料到了输出

预期数据

{
    "_id" : ObjectId("6098e6d007e2804b9c1f8317"),
   "name" : "senthil",
    "amount" : 0,
    "mobile" : null,
    "remarks" : null,
    "createdAt": "2021-05-07T13:55:34.233Z"
},
{
    "_id" : ObjectId("6098e6d007e2804b9c1f8316"),
    "name" : "periyas",
    "mobile" : null,
    "remarks" : null,
    "createdAt": "2021-05-07T13:55:34.233Z"
}

【问题讨论】:

  • 可以显示架构吗?您是否在架构选项中定义了时间戳:true?
  • @turivishal 是的,我更新了架构,请立即查看
  • 查看answer 如何在架构中启用自动时间戳,您不必在架构中添加 createdAt 和 updatedAt 字段,只需删除这两个字段即可。
  • @turivishal,我已经启用了timestamps: true 无效。另一个remarks字段未存储在默认值中。
  • 你使用的是什么 npm mongoosemongodb,什么版本?

标签: node.js mongodb express mongoose bulkinsert


【解决方案1】:

有一个大容量插入支持request in mongoose github,并由版主阅读comment之一:

initializeUnorderedBulkOp()initializeOrderedBulkOp() api 方法,被 mongodb “软弃用”。它已被 bulkWrite() API 取代,这是 MongoDB 核心 CRUD 规范的一部分,因此得到了更广泛的实施。特别是,从 4.9.0 开始,mongoose 具有 Model.bulkWrite() 函数,该函数具有验证、强制转换、承诺和 ref 取消填充。

您可以使用bulkWrite() 类似:

let data = req.body;
let bulk = [];    
data.forEach((doc1) => {
    bulk.push({ "insertOne": { "document": doc1 } });
    if (bulk.length === 5000) {
        callDispositionModel.bulkWrite(bulk).then((result) => {});
        bulk = [];
    }
})
if (bulk.length > 0) {
    callDispositionModel.bulkWrite(bulk).then((res) => {
        console.log(res.insertedCount);
        return res.send({success: true, message: 'all data uploaded successfully'})
    });
}

【讨论】:

  • 如果我使用bulkWrite API 调用。 5分钟时间太长了。我有近 15 万条记录。所以我使用了batchSize 每次调用插入 5000 条记录。
  • 你可以在bulkWrite中应用相同的batchSize逻辑,我只是​​添加示例仅供理解,你可以根据你的需要进行修改。
【解决方案2】:

改变

let dispositionSchema = new mongoose.Schema({
 name : {type: String, default: null},
 mobile : {type : String, default: null},
 remarks : {type: String, default:null},
 duration: {type : String, default: null},
 amount : {type : Number, default: 0},
 date : {type : String, default: null},
 time : {type : String, default: null},
 createdAt: {type: Date, default: Date.now },
 updatedAt: {type: Date, default: Date.now }
});

let dispositionSchema = new mongoose.Schema({
 name : {type: String, default: null},
 mobile : {type : String, default: null},
 remarks : {type: String, default:null},
 duration: {type : String, default: null},
 amount : {type : Number, default: 0},
 date : {type : String, default: null},
 time : {type : String, default: null},
 createdAt: {type: Date, default: Date.now },
 updatedAt: {type: Date, default: Date.now }
}, { timestamps: { createdAt: 'createdAt' , updatedAt: 'updatedAt'} });

More detail here

【讨论】:

  • createdAtupdatedAt 字段都可以。其他一些字段,如 timedate、``` remarks 字段不存储在 MongoDB 中。
  • 无法将默认值设为null
  • remarks 字段在数据中没有,默认值插入 MongoDB。但是,没有插入备注字段。目前,插入了三个字段,我希望在 MongoDB 中插入 6 个字段。 3 个字段用户交互值和 3 个字段架构默认值
【解决方案3】:

您现在可以在 Schema 上设置时间戳选项,让 Mongoose 为您处理:

var dispositionSchema = new Schema({..}, { timestamps: true });

【讨论】:

  • remarks: null 默认值 null 不存储在 MongoDB 中。
猜你喜欢
  • 1970-01-01
  • 2020-12-11
  • 2013-01-14
  • 2011-07-20
  • 2016-10-29
  • 2015-05-24
  • 1970-01-01
  • 2021-03-12
相关资源
最近更新 更多