有条件更新/插入和添加到数组

我有.tsv文件与一些订单信息。 重制成我的脚本后,我得到了这个。

[{"order":"5974842dfb458819244adbf7","name":"Сергей Климов","email":"wordkontent@gmail.com"}, {"order":"5974842dfb458819244adbf8","name":"Сушков А.В.","email":"mail@wwwcenter.ru"}, {"order":"5974842dfb458819244adbf9","name":"Виталий","email":"wawe2012@mail.ru"}, ... and so on 

我有一只胳膊变成mongoose。

 var ClientSchema = mongoose.Schema({ name:{ type: String }, email:{ type: String, unique : true, required: true, index: true }, forums:{ type: String }, other:{ type: String }, status:{ type: Number, default: 3 }, subscribed:{ type: Boolean, default: true }, clienturl:{ type: String }, orders:{ type: [String] } }); 

clienturl是一个由8个字符组成的密码,由函数生成。

 module.exports.arrayClientSave = function(clientsArray,callback){ let newClientsArray = clientsArray .map(function(x) { var randomstring = Math.random().toString(36).slice(-8); x.clienturl = randomstring; return x; }); console.log(newClientsArray); Client.update( ??? , callback ); } 

但我不知道如何进行更新。 只要电子邮件已经存在推入命令数组,但不能重写所有其他字段。 但是,如果电子邮件不exsists – 保存新用户clienturl等。 谢谢!

处理这个问题的最好办法是通过.bulkWrite() ,它是一个MongoDB方法,在“单个”请求中用“单一”响应发送“多个操作”。 这抵消了针对每个“循环”项目控制asynchronousfunction的问题和响应的需要。

 module.exports.arrayClientSave = function(clientsArray,callback){ let newClientsArray = clientsArray .map(x => { var randomstring = Math.random().toString(36).slice(-8); x.clienturl = randomstring; return x; }); console.log(newClientsArray); let ops = newClientsArray.map( x => ( { "updateOne": { "filter": { "email": x.email }, "update": { "$addToSet": { "orders": x.order }, "$setOnInsert": { "name": x.name, "clientUrl": x.clienturl } }, "upsert": true }} )); Client.bulkWrite(ops,callback); }; 

存在的主要思想是使用MongoDB的"upsert"function来驱动“创build或更新”function。 $addToSet仅将"orders"属性信息附加到尚未存在的数组,而$setOnInsert实际上只在动作实际上是"upsert"时才起作用, 当动作与现有文档匹配时, 才会应用$setOnInsert

通过在.bulkWrite()应用这个,当与支持它的MongoDB服务器交谈时,这成为一个“单独的asynchronous调用”,并且是任何大于或等于MongoDB 2.6的版本。

然而,特定的.bulkWrite() API的主要意义在于,如果连接的服务器实际上支持“批量”操作,API本身将会“检测”。 当它不是,这“降级”到个别“asynchronous”调用,而不是一个批次。 但这是由“驱动程序”控制的,它仍然会与您的代码进行交互,就好像它实际上是一个请求和响应一样。

这意味着处理“asynchronous循环”的所有困难实际上是在驱动程序软件中处理的。 被支持的方法否定,或者以一种简单的方式让代码“使用”来“模拟”。