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.
Related
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/
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
});
I'm getting a duplicate key error and not sure why.
I have the following schema:
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true, unique : true},
amount : {type : Number, default : 0}
}, {strict : false});
// define the schema for our user model
var userSchema = mongoose.Schema({
local : {
username : { type: String, required: true, unique: true },
password : { type: String, required: true, unique : true },
email : { type: String, required: true, unique: true },
country : { type: String, required: true },
inventory : {
food : { type : Number, default : 0},
energyDrinks : { type : Number, default : 0 }
},
wallet : [walletSchema],
lastAttackedAt : { type: Date, default: Date.now },
lastJobChange : {type: Date, default: '03/30/1988' },
lastWorked : {type: Date},
referredBy : {type : String, default : 'Admin'},
energy : { type: Number, default: 100 },
energyUpdatedAt : { type : Date, default: Date.now },
resetPasswordToken: String,
resetPasswordExpires: Date
}
},{timestamps : true});
I create a new user with this code :
...
newUser.local.username = capitalizeUser(username);
newUser.local.password = newUser.generateHash(password);
newUser.local.email = req.body.email;
newUser.local.country = req.body.country;
newUser.local.wallet.push({
// Create the default currencies
currencyName: 'Euro',
}, {
currencyName: 'Gold',
}, {
currencyName: result.countryCurrency
}
);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
Everything works fine for the first user however if I try to make another user I get MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: xyz.users.$local.wallet.currencyName_1 dup key: { : "Euro" }.
Why is this happening, doesn't each user has it's own wallet? How should I handle it, keep in mind that there are about ~230 currencies available for each user.
currencyName : {type : String, required : true}
Remove unique from there and you will be good to go. Mongo checks unique keys for collection. In your case walletSchema collection will have a lot of same values so that's why it's gives error.
As your currencyName has been set unique so it has to be different for each user you save. In fact you with this schema you won't even be able to have two users from the same country.
So to avoid this you need to remove the unique keyword from you schema and it is done. It then looks something like this.
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true},
amount : {type : Number, default : 0}
}, {strict : false});
when there is a violation of the {unique: true} schema definition in mongoose- there is an E11000 error from MongoDB and not from mongoose.
when I use schema.save(err) - mongoose does not catch this error.
any ideas how to catch it from node.js?
here is a code excerpt:
var Plan = new Schema({
slug: {type : String, default : '', trim : true, unique: true, required: true},
title: {type : String, default : '', trim : true},
body: {type : String, default : '', trim : true},
createdAt : {type : Date, default : Date.now}
})
....
// create new test records
var planArray = [
{slug: 'test', title: 'A', body: 'Lorem ipsum'},
{slug: 'test', title: 'B', body: 'Lorem ipsum'},
{slug: 'another_test', title: 'C', body: 'Lorem ipsum'}
]
var arrayLength = planArray.length;
for (var i = 0; i < arrayLength; i++) {
var p = new Plan(planArray[i])
p.save(function(err, saved){
if (err)
{console.log("error creating fixture " + err)}
})
}
Im using the following schema and code to create collection in Mongo along with the Indexer and insert data. Please note that the collection is getting created dynamically based on the categoryName.
var employeeSchema = new mongoose.Schema({
categoryId : {type: String, required: true },
loc : {type: {lon: Number, lat: Number}, index: '2d'},
// createdBy : {type: String, required: true },
createDate : {type: Date, default: Date.now}
});
exports.register = function (objEmployee , callback)
{
var emp = db.model(objEmployee.categoryName, employeeSchema );
var objSchema = new emp(objEmployee);
objSchema.save(function (err) {
if (err) return callback(err);
console.info ('Data inserted successfully.');
return callback(null);
});
};
Im able to insert data but when I run the query based on the radious, when I run I get the following error.
Sat Sep 29 20:21:24 uncaught exception: error: {
"$err" : "can't find special index: 2d for: { loc: { $within: { $center: [ [ 50.9393925139, -114.0 ], 2.0 ] } } }",
"code" : 13038
Anything going wrong with in my code ?
I think your schema definition for loc is wrong. It should be
loc: {
lon: Number,
lat: Number
}
And after your schema definition add the index
employeeSchema.index({
loc: "2d"
});