The movie is supposed to be added to the single document named as watchlist of all user, but i tried to apply unique index in combination of profile_id(user) and content_id(movie_id) so that same movie can be added to the database for different users and different movies can be added for same user. But when im trying to add the same movie after logging in with different email, the duplicate error(error.code === 11000) is still being displayed.
const mongoose = require('mongoose')
const {ObjectId} = mongoose.Schema.Types
const WatchlistSchema = new mongoose.Schema({
profile_id: { type: mongoose.Schema.Types.ObjectId, required: true, ref:'user'},
content_id:{type:Number, required:true},
mediaType:{type:String,required:true},
title:{type:String, required:true}
})
WatchlistSchema.index({ profile_id: 1, content_id: 1 },{unique: true});
const WatchListModel = mongoose.model('watchlist',WatchlistSchema)
module.exports = WatchListModel
This is the Schema and Model
WatchlistRouter.post('/list',async(req, res)=>{
const {list_id,media_type,name,ActiveUser} = req.body
try {
const user = await UserModel.findOne({email:ActiveUser})
if(user){
try {
const entry = new WatchListModel({profile_id:user._id,content_id:list_id,mediaType:media_type,title:name})
await WatchListModel.create(entry)
res.status(200).send('Added to Watchlist successfully')
} catch (error) {
if (error.code === 11000) {
res.status(400).send(`This item is already in the watchlist for this ${ActiveUser }.`);
} else {
res.status(500).send(`An error occurred: ${error.message}`);
}
}
}else{
res.status(400).send('You are not logged in to access this feature')
}
} catch (error) {
res.status(500).send({message:error.message})
}
})
This is the post operation for adding the movie
I do have an option to handle this issue in the controller by using relevant logic but i think it to be more appropriate if this is handled appropriate model design. I've tried to debug by consoling different parts and have searched the entire web but couldn't understand the reason.