Troubleshoot: KeystoneJS encountering duplicate key error when attempting to add a new item

I have searched for similar questions on this topic, but unfortunately, I haven't found a solution yet.

In my Keystone Project, I am trying to set up a Gallery similar to a post. I want to have a list of galleries, each containing a selection of images:

var keystone = require('keystone'),
    Types = keystone.Field.Types;

/**
 * Gallery Model
 * =============
 */

var Gallery = new keystone.List('Gallery', {
    map: { name: 'name' },
    autokey: { path: 'slug', from: 'name', unique: true }
});

Gallery.add({
    name: { type: String, required: true},
    published: {type: Types.Select, options: 'yes, no', default: 'no', index: true},
    publishedDate: { type: Types.Date, index: true, dependsOn: { published: 'yes' } },
    description: { type: String },
    heroImage : { type: Types.Relationship, ref: 'Image' },
    images : { type: Types.Relationship, ref: 'Image', many: true }
});

Gallery.defaultColumns = 'title, published|20%, publishedDate|20%';
Gallery.register();

While I was able to create one gallery successfully, any additional galleries result in the following error:

There was an error saving your changes: insertDocument :: caused by :: 11000 E11000 duplicate key error index: site-name.galleries.$key_1 dup key: { : null } (MongoError)

I'm unsure about what modifications I need to make in this model in order to have unique slugs for each gallery directly linked, etc.

Answer №1

To resolve the issue, it is recommended to completely remove the model from MongoDB and then restart the system. This error often occurs when modifications are made to a model containing previously defined indexes.

Answer №2

When adding a new item, it is important to assign a default value to the 'name' field since it has been set as unique=true in this case. Similarly, the 'key' should also be unique.

Initial Scenario:

MongoDB Enterprise > db.categories.save({_id: 89,name: 'xxx'})
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: sku.productcategories index: key_1 dup key: { : null }"
    }
})

Updated Scenario:

MongoDB Enterprise > db.categories.save({_id: 89,name: 'xxx', key:'xx'})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 89 })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Runescape Tracker: What essentials should I include?

Hello everyone, I am a beginner in the world of programming and I am excited to learn. I have heard that the best way to learn is by working on a project. I have always been interested in creating a Skill Tracker for my clan. Can you offer any advice on wh ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Encountering an issue with my Discord bot where it displays the error message "Unable to access property 'cache' of an undefined object"

I encountered an issue while setting up discord-xp for my bot. Whenever I attempted to use the leaderboard command, an error message popped up: username: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).username : "Unknown" ...

Exploring an XML document with HTML

I have an XML file that is paired with an XSL file. The resulting output can be located here. I am working on creating an HTML webpage where users can input a search query, such as 'Year < 2009', into a search box. The table above will then d ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

Saving an Image from HTML5 <canvas> using Java Servlet

Despite the numerous StackOverflow questions on this topic, I have gone through many of them without success. Now, I am reaching out with my own question. My objective is to save an image from an HTML5 <canvas> on my webpage to a file on my server u ...

What steps should I take to ensure I receive a response after submitting a form to a designated API?

I developed an API that retrieves data and stores it in a MongoDB database. const userDB = require('./model/user') app.post ('/signup', function (req, res){ userDB.find({username: req.body.username}). then (result=>{ ...

The process of incorporating user properties into the output of a Service Bus topic from a Javascript Azure Function

I'm currently developing a TypeScript Azure Function that utilizes an Azure Service Bus topic as its output. Although I am able to send messages successfully, I have encountered difficulties in setting custom metadata properties for the message. In m ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

Encountered error: Unable to access property 'value' as it is undefined while mapping in react components

element populateOptions() { return this.props.options.map((option, i) => ( <optgroup key={i} label={option.text}> {option.value.map((entry) => ( <option>{entry.text}</option> ))} </optg ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

Erase the contents of a div by clicking a button

I am currently working on a game project that utilizes drag-and-drop functionality, similar to Blockly and Scratch. One of the key features I am trying to implement is the ability to clear the contents of a target container by clicking a Reset button. Desp ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Javascript code generated by PHP is failing to run

When you select an option from the dropdown below: <select id='dropdown' name='dropdown' onchange='showChart(this.value)'> <option value="1">Foo</value> <option value="2">Bar</value> </select& ...

Consolidation of files for Client-Code-Generation with Swagger-Codegen: What is the best way to merge all files into

Just recently started using Swagger and NodeJS, I successfully integrated Swagger into my NodeExpress application and generated typescript-client-code with Swagger-Codegen (specifically Typescript-Angular). However, the issue I am facing is that the gener ...