Add and Remove Within Mongoose Add and Remove Within Mongoose mongodb mongodb

Add and Remove Within Mongoose


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:

db.collection.update(    { "username": "walterwhite" },    {  $push:         {             favourites: [ { "user_id": "7" } ]        }     } )


First of all you will need routes for any of the actions. It's probably the best practice to use the HTTP Verbs (GET/POST/PUT/DELETE etc.). Then your routes would look something like this: (this could be wrapped in a file that contains all routes and later required in the main app file (ex. app.js).)

module.exports = function (router) {router.route('/favourites')        .get(function (req, res, next) {            // Code for getting all items        })        .post(function (req, res, next) {            // Code for inserting new item        })        .delete(function (req, res, next) {            // Code for deleting an item        });}

Then you will need to build a form with fields corresponding to the item's properties and use POST as a submit method. You will need it for inserting (adding) new items. The request sent from the form, will send you to the post route, where you will handle your logic for appending item to the list.
To implement the deletion you will have to send a DELETE, request passing an identifier of the item you'd want to delete. You will handle this code in the delete route.
Of course, the get route is for getting all items in the collection for further processing or visualizing.


you must create an object id associated to every user_id. you can create such id's using.you can associate multiple models with mongoose population

var Schema = mongoose.Schema;var ObjectId = Schema.ObjectId;"favourites" : [     {        "_id" : ObjectId("57338c9cc5c8cf74181b4cff"),        "user_id" : 1    },     {          "_id" : ObjectId("5734588e5a54d45434693a09")        "user_id" : 2    }]

either render the page or send a json object as response with the object id in it as per your setup.

<a href="#" id="5734588e5a54d45434693a09">user_id-2</a> <a href="#" id="57338c9cc5c8cf74181b4cff">user_id-1</a> 

now you can make an ajax request with the object id when clicked on a particular <a> tag.you can achieve this with jquery. Then remove the user associated with that id from your favorites.

If you add more details.I can give you a specific answer.