mongodb添加多条数据_node.js – 在MongoDB中使用mongoose批量插入多个集合

我有2个集合(data,metaData)

数据模式是

{

_id: ......,

name: ......, //not unique

mobile: ......, // unique or null

email: ......, // unique or null

uniqueId: ......, // unique or null

}

插入需要至少一个唯一数据

元数据架构是

{

_id: ......,

dataId: ......,//refrence from _id of data collection

key: ......,

value: ......

}

JSON数组来自客户端

[{

name: "abc",

mobile: 9999999999,

mData: {

c1: 123,

c2: "xyz"

}

},

{

name: "qwerty",

email: 'qwerty@mail.com',

mData: {

c1: 123,

c2: "zxc"

}

}

......

]

我正在迭代数组并将它们中的每一个插入到MongoDB中.

let Bulk = Data.collection.initializeUnorderedBulkOp();

dataArr.forEach(function(item) {

let data = service.generateData(item);

// data.query: {mobile: ..., email: ..., uniqueId: ...}

// if value exists then keys is also exists for mobile, email, uniqueId in query

Bulk.find(data.query).upsert().updateOne(data.doc);

});

Bulk.execute((e, d) => {

let metaBulk = MetaData.collection.initializeOrderedBulkOp();

let length = dataArr.length;

dataArr.forEach(function(data) {

Data.findOne(data.query).exec(function(err, data) {

length--;

for(let key in data["mData"]) {

let value = data["mData"][key] || "";

let mData = service.generateMdata(key, value, data._id);

metaBulk.find(mData.query).upsert().updateOne(mData.doc);

}

if(length == 0) {

metaBulk.execute();

}

});

});

});

我的解决方案现在工作正常但是它花了很多时间来迭代数据收集以查找metaData集合的ID.

我需要一种将数据批量插入MongoDB而无需查询数据ID的方法.是否有任何选项可以在单个查询中使用mongoose对多个集合执行批量upsert.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值