6

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.