I am having below schema in my API which gets details of username and the products he added to the cart.
const mongoose = require('mongoose');
mongoose.connect('mongodb connection').then(()=>{
console.log('DB connection is successfull');});
const AutoIncrement = require('mongoose-sequence')(mongoose);
const cartSchema = new mongoose.Schema({
cartId : {
type : Number
},
username : {
type : String
},
productsInCart : [{
productId : {type : Number,required : true},
productName : {type:String},
quantity : {type:Number}
}],
statusOfCart : {
type : String,
default : 'Open'
}},{ timestamps: true });
cartSchema.plugin(AutoIncrement,{id : 'cart_seq',inc_field : 'cartId'});
let cartModel = mongoose.model('carts',cartSchema);
module.exports = cartModel;
As you can see in the above code I am also using the mongoose-sequence to make cartId as a auto-incremented field.
Now, I have a POST request which gets the below JSON in request body and adds it to the cart collection in the MongoDB using the create method.
{ "username":"admin", "productsInCart": [ { "productId":1, "productName":"Watch", "quantity":4 }, { "productId":2, "productName":"Phone", "quantity":5 } ] }
The code inside the Route Handler for the POST request in Express API would look something like this
let ctMod = new cartModel();
ctMod.username = req.body.username;
ctMod.productsInCart = req.body.productsInCart;
let insCartData = await cartModel.create(ctMod,{new:true});
if(insCartData.length > 0)
{
return res.status(200).json({
message : `New items got inserted into the cart with the ID : ${insCartData.cartId}`,
data : insCartData
});
}
The above code inserts two entries into the collection like below instead of one
{ "statusOfCart": "Open", "productsInCart": [], "createdAt": "2021-01-04T15:25:35.188Z", "updatedAt": "2021-01-04T15:25:35.188Z", "cartId": 13, "__v": 0 }, { "statusOfCart": "Open", "productsInCart": [ { "_id": "5ff332a891aa170b60a21ea9", "productId": 1, "productName": "Watch", "quantity": 4 }, { "_id": "5ff332a891aa170b60a21eaa", "productId": 2, "productName": "Phone", "quantity": 5 } ], "username": "admin", "createdAt": "2021-01-04T15:25:35.210Z", "updatedAt": "2021-01-04T15:25:35.210Z", "cartId": 14, "__v": 0 }
can you help me understand why there is duplicate entries in my db?