Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate entries in array in Mongoose schema

User schema:

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 to add values to blog_bookmarks for a particular 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 blog_id to blog_bookmarks array only if it doesn't exist, I don't want multiple entries.

Currently, user.find() gives console error

user.find() is not a function

How to achieve it?

like image 282
kRAk3N Avatar asked Jul 03 '16 00:07

kRAk3N


1 Answers

For avoiding duplicate values in your blog_bookmarks, use the $addToSet operator.

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

Your user.find() gives you probably an error because it should be User.find() with a capital U at the beginning.

like image 185
DAXaholic Avatar answered Nov 03 '22 00:11

DAXaholic