node.js - 将多个文档插入 MongoDB,同时需要唯一索引

标签 node.js mongodb

我的集合Pphone字段上有一个唯一索引:

db.P.ensureIndex( { phone: 1 }, { unique: true, dropDups: true } )
db.P.insert( {phone:"555-1234"} )

如果我插入一组文档,其中甚至一个文档都有重复的键:

db.P.insert( [{phone:"911"},{phone:"555-1234"}] )
> E11000 duplicate key error index: test.P.$phone_1  dup key: { : "555-1234" }

整个插入失败,没有插入有效的数字。

问题:如何进行批量插入、确保插入有效文档并获取有关哪些插入失败的信息? 使用 Nodejs api 显示代码的奖励积分。

最佳答案

MongoDB 驱动程序有一个“ContinueOnError”选项,该选项会导致 mongo 跳过具有重复唯一键的记录。至于确定跳过的内容,根据文档:“如果批量插入期间发生多个错误,客户端只会收到生成的最后一个错误。( http://docs.mongodb.org/manual/core/bulk-inserts/ )。

对于 Node.js,它会是这样的

db.P.insert( [{phone:"911"},{phone:"555-1234"}], {continueOnError:true} )

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#insert

关于node.js - 将多个文档插入 MongoDB,同时需要唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21464644/

相关文章:

android - Mlab 包含查询

javascript - Mongoose版本错误: No matching document found for id when document is being saved

node.js - Mongoose 聚合匹配不适用于正则表达式

javascript - 将逻辑添加到 Mongoose 的 Model ctor 中的最佳实践是什么?

java - 连接到 MongoDB Atlas : com. mongodb.MongoCommandException: Command failed with error 8000

javascript - bcrypt.js 比较方法如何知道加盐轮数?

node.js - 将 npm 配置传递到 npm 脚本条目中

javascript - Node 的 Browserify 是否绕过了 Javascript 的沙箱?

javascript - 如何使用 Mongoose 从集合中的所有文档中删除字段?

node.js - 启动工头时出错(Dotenv::FormatError)