I'm trying to intergrate in my api the possibility to create a user. I'm using node and mongodb. Here is my schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FileSchema = new Schema({
name: {
type: String,
required: true,
minlength:1,
unique:false,
}, extension: {
type:String,
required:true,
unique:false,
}, content: {
type:String,
required:true,
unique:false,
},group:{
type:String,
required:false,
unique:false,
}, creator:{
type: String,
required: true,
unique:false,
}
})
const File = mongoose.model('File', FileSchema);
module.exports = File;
And here is my function:
const createNewFile = (req, res) => {
const name = req.body.name;
const extension = req.body.extension;
const creator = req.body.creator;
const group = req.body.group;
console.log(req.body)
const newFile = new File({name, extension, content:'Write your code here',creator, group:group});
newFile.save()
.then(() => res.json('200'))
.catch(err => res.status(400).json('ERROR:' err))
}
And the Insomia and Postman console returns the error that is in the title. What can I do to avoid this error? I added unique: false because I read it in another quesion , but it failed anyway. Can someone please help me? When the db is empty, I can create the first element. Then, when I create the second one, the errors arrives. PLease help me
CodePudding user response:
In the mongodb node there is a unique index on {key: 1} in the files collection of the myFirstDatabase database.
I suspect this was created when you were testing potential schema designs.
In order to insert documents that do not contain unique values for that field, including not including the field, that index will need to be removed.
Several ways to accomplish that:
- connect to mongod with the mongo shell, or admin tool like Compass or Robo3t and drop the index manually
- use
syncIndexesprovided by Mongoose - drop the
filescollection - drop the
myFirstDatabasedatabase - stop the mongod, remove the entire dbpath, and start over with a clean instance
