我正在尝试使用insertMany在Group集合中插入多个'groups',但它(在插入第一个项目后总是引发错误..
>db.groups.insertMany([{"name":"GroupA","description":"Description GroupA"},
{"name":"GroupB","description":"Description GroupB"},
{"name":"GroupC","description":"Description GroupC"}])
插入第一项
{ "_id" : ObjectId("593ad787da6a6eba2994dfb6"), "name" : "GroupA",
"description" : "Description GroupA" }
错误
2017-06-09T19:14:47.537+0200 E QUERY [thread1] BulkWriteError: write error at item 1 in bulk operation :
BulkWriteError({
"writeErrors" : [
{
"index" : 1,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: cockpit-api-test.groups index: roles.name_1 dup key: { : null }",
"op" : {
"_id" : ObjectId("593ad787da6a6eba2994dfb7"),
"name" : "GroupB",
"description" : "Description GroupB"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:372:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:336:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1173:1
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:302:5
@(shell):1:1
怎么了? 感谢您的反馈
群组模型
/**
* Role Schema
*/
const RoleSchema = new Schema({
name: { type: String, unique: true, required: true },
description: { type: String, required: false, trim: true, },
createdAt: { type: Date, default: Date.now }
});
/**
* Group Schema
*/
const GroupSchema = new Schema({
name: { type: String, unique: true, required: true },
description: { type: String, required: false, trim: true, },
roles: [RoleSchema],
createdAt: { type: Date, default: Date.now }
});
答案 0 :(得分:0)
我认为问题是您在进行批量写入时没有将Observable.defer(() ->
someCondition()
? service.setSolicitation("Berlin", getString(R.string.api_key))
: service.createSolicitation(....)
)
.subscribeOn(Schedulers.io())
// Read results in Android Main Thread (UI)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::processError);
或roles.name
插入您的mongo。默认情况下,如果没有定义,mongo会将其设置为null。
首次运行时,您的代码会在数据库中插入null,因为roles.description
未定义
roles
第二次运行{"name":"GroupA","description":"Description GroupA", "roles": {"name": null, "description": null }
仍未定义,因此将输入另一个空值
roles
您的{"name":"GroupB","description":"Description GroupB", "roles": {"name": null, "description": null}
不允许重复的RoleSchema
值,因为您设置了name
抛出错误中的unique: true
指出了重复的空错误。