0

I have no clue what is going on. I started using 'required' values in the userSchema and after getting this error I removed the required specification but to no avail. I can create one item with no problem but any submissions after that throws an error.

here is my schema:

const mongoose = require('mongoose')

const ItemSchema = new mongoose.Schema(
    {
    creator: { type: String, required: true },
    name: { type: String, required: true },
    category: { type: String, required: true, default: 'drink' },
    price: { type: Number, required: true, default: 0.00 },
    ingredients: { type: String, default: 'none' }
    },
    { collection: 'item'}
)

const model = mongoose.model('ItemSchema', ItemSchema)

module.exports = model

here is how I am saving the content to db:

app.post('/admin', async (req, res) => {
    const { creator, name, categoryChoice, itemPrice, ingredients } = req.body
    console.log(req.body)
    try {
        const response = await Item.create({
            creator, 
            name, 
            categoryChoice, 
            itemPrice, 
            ingredients
        })
        console.log("item created successfully", response)
        return res.json({ status: 'ok', response })
    } catch (error) {
        console.log(error)
        return res.json({ status: 'error', error })
    }
})

app.listen(process.env.PORT, () => {
    console.log(`listening on port ${process.env.PORT}`)
})

and lastly the error message:

MongoServerError: E11000 duplicate key error collection: login.item index: item_1 dup key: { item: null }

index: 0,
code: 11000,
keyPattern: { item: 1 },
keyValue: { item: null },
[Symbol(errorLabels)]: Set {}

to reproduce this error I would delete the only existing item in the collection and then create an item (again, the first time I create an item it gives me no problems), and then I would attempt to create another item which would then throw me an error. Thank you in advance for the help.

I saw a similar problem here but I think in this case it has more to do with the "unique" identifier in the user schema (feel free to correct me if I am wrong or misunderstanding something)

asantaems
  • 1
  • 2
  • May be there is an unique index created in the database already - you may want to see if such index exists. From `mongosh`, try this command: `db.item.getIndexes()`. – prasad_ Aug 09 '22 at 07:20
  • I checked the indexes as you said and you were right. There were indexes saved with the "unique" identifier from previous iterations of my item model. Thanks a lot! – asantaems Aug 09 '22 at 09:12

0 Answers0