E11000 duplicate key error index: id - node.js

i've created an api which works fine and i have added a user through an post requet however when i try to add another user with a different id i get this error:
SUCCESS: {
code = 11000;
errmsg = "E11000 duplicate key error index: matchmaking.users.$id_1 dup key: { : null }";
index = 0;
op = {
"__v" = 0;
"_id" = 352523;
birthday = "1998-10-09T23:00:00.000Z";
country = denmark;
name = Frederik;
};
}
UserSchema
var userSchema = new Schema({
_id: {
type: SchemaTypes.Long,
required: true,
unique: true
},
accessToken: String,
email: String,
name: String,
birthday: Date,
country: String,
created_at: Date,
updated_at: Date
});

Related

Mongoose / MongoDB duplicate entries with unique key in schema

I dont know why this happens, I have a schema with a unique key for the field "address" but I get duplicate entries. I also check before I insert a new document if Model.exists() and it still inserts documents. I have no idea why, also I am getting occasional duplicate entry errors in the console. This is my code
const Schema = mongoose.Schema(
{
address : { type: String, unique: true },
isContract : { type: Boolean, required: true, default: false },
ethervalue : { type: Number, default: 0 },
symbol : { type: String, unique: true },
tokenname : { type: String},
divisor : { type: Number },
tokentype : {type: String},
bluecheckmark: {type : Boolean, default: false},
description: {type: String},
totalsupply: {type: Number},
},
{ timestamps: true }
);
async saveAddress(address) {
try {
const exists = await Address.exists({ address: address });
if (!exists) {
const isContract = await this.isContract(address);
let temp = new Address();
if (isContract) {
const info = await etherscan.getTokenInfoByContractAddress(address);
temp.isContract = true;
if(info.status == 1){
temp.symbol = info.result[0].symbol;
temp.tokenname = info.result[0].tokenName;
temp.totalsupply = info.result[0].totalSupply;
temp.divisor = info.result[0].divisor;
temp.tokentype = info.result[0].tokenType;
temp.description = info.result[0].description
temp.bluecheckmark = info.result[0].blueCheckmark
}
}
temp.address = address;
await temp.save();
}
} catch (error) {
console.log('saveAddres()', error.message);
}
}
To prevent duplicate entries in mongodb, you can add a unique index on that particular field. In this case: db.collection.createIndex({"address":1},{unique:true}) .
Refer: https://docs.mongodb.com/manual/core/index-unique/

Node.js Auto Increment E11000 duplicate key error collection

I'm struggling with Error E11000 duplicate key error collection, I have a schema with another sub-schema array and when I try to insert my schema with the empty array I allways get this error. I tried to set it undefined on pre-save without sucesss... I have deleted my schem from mongoDB and its indexes. The error appears after I insted **autoincrement **in Marker schema.
City Schema:
let mongoose = require('mongoose');
let autoIncrement = require('mongoose-auto-increment');
let Marker = require('./marker');
var MarkerSchema = require('mongoose').model('marker').schema;
//City Schema
//status : 1 Ok, 2 Hidden, 3 Deleted
let citySchema = mongoose.Schema({
id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
status: {
type: Number,
required: true
},
coordinates: {
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
}
},
markers: [MarkerSchema]
});
citySchema.pre('save', function (cb) {
console.log('pre save');
if (this.markers && this.markers.length === 0) {
this.markers = undefined;
}
cb();
});
citySchema.plugin(autoIncrement.plugin, {
model: 'city',
field: 'id',
startAt: 1,
incrementBy: 1
});
let City = module.exports = mongoose.model('city', citySchema);
marker schema
let mongoose = require('mongoose');
let autoIncrement = require('mongoose-auto-increment');
let markerSchema = mongoose.Schema({
status: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
coordinates: {
latitude: {
type: Number,
required: true
},
longitude: {
type: Number,
required: true
}
}
});
markerSchema.plugin(autoIncrement.plugin, {
model: 'marker',
field: 'id',
startAt: 1,
incrementBy: 1
});
let Marker = module.exports = mongoose.model('marker', markerSchema);
Having the same issue ...
Rather sure this is caused by the mongoose-auto-increment module...
try this:
let citySchema = new mongoose.Schema({
id: {type: Number, default: 0, unique: true},
....
I think the error is because you have not defined an initial value where the auto-increment should work and the fact that it is not declared as unique ?
I know this is an old question but for future viewers here is what i did.
I added a type of number on the plugin schema and set unique to false to avoid duplication during manipulation.
so the new plugin schemas will be
markerSchema.plugin(autoIncrement.plugin, {
model: 'marker',
field: 'id',
startAt: 1,
incrementBy: 1,
type: Number,
unique: false
});
and
citySchema.plugin(autoIncrement.plugin, {
model: 'city',
field: 'id',
startAt: 1,
incrementBy: 1,
type: Number,
unique: false
});

How to add validation on mongoose child element in a schema?

Sorry if this is obvious, but I googled for hours and most result is related to sub-document/nested-schema, which is for array of object and not my case.
For simplicity, I just construct a minimal object, but the concept is the same.
I have a mongoose Schema as follow, I want to validate father object by validateFunction, which the validateFunction is just checking if firstName/lastName exists or not:
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: String
},
mother : {
firstName: String,
lastName: String
}
};
I have tried
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
type: {
firstName: String,
lastName: String
},
validate : validateFunction
},
mother : {
firstName: String,
lastName: String
}
};
Which seems to work, but after reading Mongoose Schema Type, it seems the type is not a valid type in mongoose.
Can someone point me the proper way to add validation on a child object(father)?
Note: I have check this SO which is similar, but I don't want to store 'father' in a separate collection as the Person is the only object that use 'father', so I think father so be inside 'Person' object.
Edit: I have tested #Azeem suggestion with the following code:
var log = function (val) {
console.log(val);
return true ;
}
var validateFunction = function (val) {
if (typeof val === 'undefined') {
return false;
}
console.log(typeof val, val);
return true;
}
var many = [
{ validator: log, msg: 'fail to log' },
{ validator: validateFunction, msg: 'object is undefined' }
];
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: {type : String }
validate : many // following http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate
},
mother : {
firstName: String,
lastName: String
}
});
var PersonModel = mongoose.model("PersonTest", PersonSchema);
var josephus = new PersonModel({firstName:'Josephus', father:{lastName:null}});
josephus.save(function(error) {
console.log("testing", error);
})
and got error
***/index.js:34
validate : many
^^^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:945:3
if the schema is changed to the following one, it works (prove of validate function running properly)
var PersonSchema2 = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: {type : String ,validate : many}
},
mother : {
firstName: String,
lastName: String
}
});
I have a example where i put small validation in my moongoose schema, hope it may help.
var UserType = require('../defines/userType');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Schema for User
var UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String
},
password: {
type: String,
required: true
},
dob: {
type: Date,
required: true
},
gender: {
type: String, // Male/Female
required: true
default: 'Male'
},
type: {
type: Number,
default: UserType.User
},
address:{
streetAddress:{
type: String,
required: true
},
area:{
type: String
},
city:{
type: String,
required: true
},
state:{
type: String,
required: true
},
pincode:{
type: String,
required: true
},
},
lastLocation: {
type: [Number], // [<longitude>, <latitude>]
index: '2d', // create the geospatial index
default: [77.2166672, 28.6314512]
},
lastLoginDate: {
type: Date,
default: Date.now
},
});
//Define the model for User
var User;
if(mongoose.models.User)
User = mongoose.model('User');
else
User = mongoose.model('User', UserSchema);
//Export the User Model
module.exports = User;
Like this, you can add further validation. In your mongo query, just check
db.collection.validate(function(err){
if(err){
console.log(err); //if your validation fails,you can see the error.
}
});
Try this
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
firstName: String,
lastName: String
validate : validateFunction
},
mother : {
firstName: String,
lastName: String
}
};
Required Validators On Nested Objects
mongoose docs actually suggest to use nested schema, so we can do validation on an object.
var ParentSchema = new Schema({
firstName: String,
lastName: String
});
var PersonSchema = new Schema({
firstName : String,
lastName : String,
father : {
type: ParentSchema,
validate : validateFunction
},
mother : {
type: ParentSchema,
validate : validateFunction
}
};
This should do the tricks and do validation.

Mongoose + Expressjs - E11000 duplicate key error index?

I don't understand why I got this error below after adding the first entry:
E11000 duplicate key error index: mydb.datasets.$id_1 dup key: { : null }
I don't have any null value in my first entry:
{
"index" : "9IPZMW7IL",
"name" : "Tweets",
"owner_name" : "xxx",
"read_key" : "fb6f9125f4ca15c33fea89416c3351d1",
"write_key" : "d8a6c7e5fc73b5a91aa7a533565ed1f1",
"data" : {
"var1" : {
"name" : "particles"
}
},
"_id" : ObjectId("57729dc20cb70952424cdbb4"),
"created_at" : ISODate("2016-06-28T15:54:42.576Z"),
"entries_number" : 0,
"public" : true,
"__v" : 0
}
Below is my code:
// CRUD API:
// POST/ Create new dataset request
router.post("/", helper.authenticate, function(req, res) {
// Used to set the dataset owner
var sessionUser = req.session.user.name;
// Get values from the post request
var name = req.body.name;
var isPublic = req.body.public != undefined ? true:false;
// Delete the values from the request body so that we only keep information about the variables
delete req.body.name;
delete req.body.public;
// This is so that we can loop through the object in reverse order
// We do that so that the fields are saved in the right order on the db
// (this way it will appear in the right order on the 'edit' view)
var propertiesList = [];
for (var property in req.body) {
if (req.body.hasOwnProperty(property)) {
propertiesList.push(property);
}
}
propertiesList.reverse();
var variablesFields = {};
for (var i in propertiesList) {
console.log(propertiesList[i])
variablesFields[propertiesList[i]] = {name:req.body[propertiesList[i]],
values: Array};
}
// Create dataset
Dataset.create({
index: helper.uniqueIndex(),
name: name,
owner_name: sessionUser,
read_key: hat(),
write_key: hat(),
public: isPublic,
data: variablesFields
}, function(err, dataset) {
if (err) {
console.log("Error creating the dataset: " + err);
req.session.error = "A problem occured when creating the dataset. Please try again.";
} else {
console.log("New dataset created with id: " + dataset._id);
req.session.success = "Dataset " + name + " created successfully.";
}
res.redirect("/index");
});
});
Error:
Error creating the dataset:
WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key
error index: mydb.datasets.$id_1 dup key: { : null
}","op":{"index":"2IPZMWHGI","name":"PM
2","owner_name":"xxx","read_key":"fc31c152aa86070252c70c0304e4ca5c","write_key":"238110753c8762ce4a547fa02100a299","data":{"var1":{"name":"particles"}},"_id":"57729dcf0cb70952424cdbb5","created_at":"2016-06-28T15:54:55.459Z","entries_number":0,"public":true,"__v":0}})
Model:
var datasetSchema = new mongoose.Schema({
index: {type: String, required: true, index: {unique: true}},
name: {type: String, required: true},
owner_name: {type: String, required: true},
read_key: {type: String},
write_key: {type: String},
public: {type: Boolean, default: false},
data: {type: Object},
entries_number: {type: Number, default: 0},
created_at: {type: Date, default: Date.now},
last_entry_at: {type: Date}
});
Any idea why and how I can fix this?
I solved it by removing a "id" key that I initially declared as
id: { type: String, unique: true, required: true},
I removed this line and deleted the initial collection and that solved the issue.

Object has no method '__super__'

I extends mongoose save function:
User Schema is:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var UserSchema = new mongoose.Schema({
Name: String,
Surname: String,
login: {type: String, required: true},
Password: {type: String, required: true},
email: { type: String, index: { unique: true } },
Age: Number
});
And extended method is:
UserSchema.methods.save = function(okFn, failedFn) {
if (this.isValid()) {
this.__super__(okFn);
} else {
failedFn();
}
};
And on 'save' try it gives me error:
TypeError: Object { object fields and values } has no method '__super__'

Resources