Reputation: 43
{
"_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.
Upvotes: 3
Views: 812
Reputation:
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" } ]
}
}
)
Upvotes: 2
Reputation:
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.
Upvotes: 0
Reputation: 1700
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.
Upvotes: 1