John Pile John Pile - 1 year ago 103
Node.js Question

Add and Remove Within Mongoose

"_id" : 1,
"_name" : "peter",
"favourites" : [
"user_id" : 1
"user_id" : 2

I have this schema within Mongo, and I'm using Node/Express/Mongoose to manage my stack. I'm new to this particular stack and I have a 'favourite' button on the website I'm building. What's the best way to add/remove from favourites?

Do I really need to setup two routes, one for POST and another for PUT? I'm not sure what the best way is to solve this particular problem, I've done some searching and I've not found anything that relevant.

Xiy Xiy
Answer Source

I'm not going to give you the full answer as it's always good to learn, so I've give you 90% of what I think is what you're looking for. Do a check for the name and if it doesn't exist within the favourites array, do the following:

    { "username": "walterwhite" },
    {  $push: 
            favourites: [ { "user_id": "7" } ]