Prevent duplicate entries in an array in Mongoose schema

Custom Scheme:

var UserSchema = new Schema({ name: { type: String, required:true }, email: { type: String, required:true, lowercase: true , index : { unique: true } }, password : { type: String, required:true , select:true }, blog_bookmarks: [{ type: String }] }); 

API for adding values ​​to blog_bookmarks for a specific user

 api.post('/add_bookmark_blog', function(req, res){ User.findOne({_id: req.query.user_id}, function(err, user){ if(err) { res.json(err) } else{ var blogid = req.body.blog_id; user.find({ blog_bookmarks : blogid}, function(res1, result){ if(res1){ user.blog_bookmarks.push(blogid); user.save(function(err) { if(err){ res.json('ERROR at adding bookmark') } else { res.json('bookmark for blog added') } }) } else{ res.json('Already bookmarked') } }); } }) }); 

I want to add the blog_id array to blog_bookmarks only if it does not exist, I do not want several entries.

user.find() is currently displaying a console error

user.find () is not a function

How to do it?

+5
source share
1 answer

To avoid duplicate values ​​in blog_bookmarks , use the $ addToSet statement .

 User.update({_id: req.query.user_id}, {$addToSet: {blog_bookmarks: blogid}}) 

Your user.find() is probably giving you an error, because it should be user.find() with capital U at the beginning.

+5
source

All Articles