Schema (../models/add.js)

var addSchema = new Schema({ name: {type: String, unique: true, sparse: true}, phone: Number, email: String, country: Number }); module.exports = mongoose.model('Contact', addSchema);

add-manager.js

var Add = require('../models/add.js'); var AM = {}; var mongoose = require('mongoose'); module.exports = AM; AM.notOwned = function(country, callback) { Add.update({country: country}, {country: country}, {upsert: true}, function(err, res){ if (err) callback (err); else callback(null, res); }) }

news.js

// if country # is not in the database AM.notOwned(country, function(error, resp){ if (error) console.log("error: "+error); else { // do stuff } })

error:

MongoError: E11000 duplicate key error index: bot.contacts.$name_1 dup key: { : null }

After seeing the error message, I googled around and learned that when the document is created, since name isn't set, its treated as null. See Mongoose Google Group Thread The first time AM.notOwned is called it will work as there isn't any documents in the collection without a name key. AM.notOwned will then insert a document with an ID field, and a country field.

Subsequent AM.notOwned calls fails because there is already a document with no name field, so its treated as name: null, and the second AM.notOwned is called fails as the field "name" is not set and is treated as null as well; thus it is not unique.

So, following the advice of the Mongoose thread and reading the mongo docs I looked at using sparse: true. However, its still throwing the same error. Further looking into it, I thought it may be the same issue as: this , but setting schema to name: {type: String, index: {unique: true, sparse: true}} doesn't fix it either.

This S.O. question/answer leads me to believe it could be caused by the index not being correct, but I'm not quite sure how to read the the db.collection.getIndexes() from Mongo console.

db.contacts.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "ns" : "bot.contacts", "name" : "_id_" }, { "v" : 1, "key" : { "name" : 1 }, "unique" : true, "ns" : "bot.contacts", "name" : "name_1", "background" : true, "safe" : null } ]

What can I do to resolve this error?

Problem courtesy of: thtsigma

本文数据库(综合)相关术语:系统安全软件

代码区博客精选文章
分页:12
转载请注明
本文标题:Using sparse: true still getting MongoError: E11000 duplicate key error
本站链接:https://www.codesec.net/view/621393.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(综合) | 评论(0) | 阅读(44)