I am connected to my database using node.js. Now I want to send some data to the database which is as follows:
data
const service=[
{ServiceChoseByUser:'Cleaning',PriceForService:'100'},
{ServiceChoseByUser:'Painting',PriceForService:'300'},
{ServiceChoseByUser:'Electrician',PriceForService:'400'},
{ServiceChoseByUser:'Plumbing',PriceForService:'50'},
// may be increased as the number of services selected by the user.
}
My schema is described as :
Schema.js
import mongoose from 'mongoose';
const serviceSchema = new mongoose.Schema({
service: [
{
id: {
type: String,
trim: true,
unique: true
},
ServiceChoseByUser: {
type: String,
trim: true,
unique: true,
lowercase:true
},
PriceForService: {
type: String,
trim: true,
lowercase:true,
unique: true,
},
},
]
});
let Service = mongoose.model('service', serviceSchema);
export default Service;
And my controller of data is :
controller.js
import Service from ".Schema.js";
export const sendService = async (req, res) => {
try {
const serviceByUser = req.body;
console.log(serviceByUser);
const newService = new Service(service);
console.log(newService);
await newService.save();
console.log('Service data stored');
res.send(200 + 'Service data stored')
} catch (error) {
res.send(500 + ' Error occured');
console.log('Error: from service controller ', error.message);
}
}
The app is connected successfully to the database. But when I am sending data to the database, it always shows Error: from service controller E11000 duplicate key error collection: HouseDeck-Cluster.services index: services_1 dup key: { services: null }
I checked for that by using console.log() as you can see in controller.js. When I am displaying the data it shows the data is correct but when I do console.log(newService). It always shows { _id: new ObjectId("6234720c80a5f440ade88d24"), service: [] }
It states that something is wrong with the schema. I tried various things like:
Already Tried These For Schema
1. service=[Object]
2. service=[
{
id:String,
ServiceChoseByUser:String,
PriceForService:String
}
]
3. service=Array
4. service={
type:Array
}
5. service=[
{
type:Object
}
]
6. // already provided above
I tried many things, also searched for it, read the documentation but I couldn't find any solution.
Please help