I have been looking through reddit and n have tried the solutions in the following links but have not worked. E11000 duplicate key error index in mongodb mongoose
Basically I have a list schema and a user schema and I want to index to have a user and a list name associated with it. Here is my list schema:
import mongoose from 'mongoose'
const listSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
maxLength: 50
},
description: String,
createdBy: {
type: mongoose.SchemaTypes.ObjectId,
ref: 'user',
required: true
}
},
{ timestamps: true }
)
listSchema.index({ user: 1, name: 1 }, { unique: true })
export const List = mongoose.model('list', listSchema)
This is my controller (its generic for other schemas but it works for them)
export const createOne = model => async (req, res) => {
console.log('logging user id', req.user._id)
const createdBy = req.user._id
try {
const doc = await model.create({ ...req.body, createdBy: createdBy })
res.status(201).json({ data: doc })
} catch (e) {
console.error(e)
return res.status(400).end()
}
}
Everytime I pass in the user I get the user as null as an error.
MongoError: E11000 duplicate key error collection: api-design.lists index: user_1_name_1 dup key: { user: null, name: "08/29/2020" }
driver: true,
index: 0,
code: 11000,
keyPattern: { user: 1, name: 1 },
keyValue: { user: null, name: '08/29/2020' }
user appears as null even though i passed in their ._id from the other collection
Can anyone help me out please? I have tried dropping the indexes from the collection and dropping all the lists already.