I'm working on my frist full stack MERN project and could use some help. I would like to have a collection of users in MongoDB, where every user starts with an empty array. However, I am getting the following error message when I try to post new users:
MongoError: E11000 duplicate key error collection: learnGreek.users index: words.greek_1 dup key: { words.greek: null }
A little bit about what I'm trying to achieve. I am trying to make a Greek language learning app where the user can add their own words and then quiz themselves on on the words they have added.I want to record how many times in a row the user has gotten the word right and the last time they tackled the word. Therefore, my current model and schemas look like the folowing:
const wordSchema = new Schema({
"greek": {
"type": String,
"required": true,
"trim": true,
"minlength": 1
},
"english": {
"type": String,
"required": true,
"minlength": 1
},
"success":{
"type": Number,
"required": true
},
"timeStamp":{
"type": Date,
"required":true
}
});
const userSchema = new Schema({
eMail: {
type: String,
required: [true, "Please Enter an e-mail"],
trim: true,
minlength: 3,
validate: [isEmail, "please enter a valid-email"],
unique: true
},
password: {
type: String,
required: [true, "Please Enter a password"],
trim: true,
minlength: [8, '"Minminum password length is 8 characters'],
},
words: [wordSchema]
});
The first time I used this model, everything worked, but every time since then I have recieved the "E11000 duplicate key error collection" error.Now when I googled this error message, what I read (and understand) on the matter is that Mongoose is rejecting my new users because their empty word arrays are not unique. One solution proposed was to add the sparse property to my schema, but I am unsure where to use it in my schema. I have tried...
words: {[wordSchema] , sparse: true }
... but that gives me a syntax error.
I have also tried
const wordSchema = new Schema({
**"sparse":true,**
"greek": {
"type": String,
"required": true,
"trim": true,
"minlength": 1
},
"english": {
"type": String,
"required": true,
"minlength": 1
},
"success":{
"type": Number,
"required": true
},
"timeStamp":{
"type": Date,
"required":true
}
});
but I then received the following error message:
TypeError: Invalid schema configuration:
Trueis not a valid type at pathsparse. See snip for a list of valid schema types.
What is the best way for me to be able to save each user so that they start with an empty array that they will populate with their own words that they will add once they start using the application?