Reputation: 4998
This question doesn't answer my question: Delete an element from an array of an array in MongoDb
I've created a very basic MEAN application. I'm creating (or trying to create) a stackoverflow kind of mechanism. I've an article on which there are upvotes and downvotes. Here's a screenshot of mongodb record. There are many such records:
You can see there's an array of upvoters
and downvoters
. I've a case where the current logged in user who previously upvoted an article now wants to downvote the same article. Then his name should be shifted from 'upvoters' array to downvoters
array. This involves two steps:
upvoters
arraydownvoters
array.Step no. 2 I can do. But step 1 I'm facing problem with. Here's my code. Focus on removeUserFromUpvotersList()
method:
article.component.ts
export class ArticleComponent implements OnInit {
articleId : String = '';
article;
currentLoggedInUserId: string;
updatedVotes={
articleid: "",
upvotes: 0,
downvotes: 0,
upvoters: [],
downvoters: []
};
...
downvoted() {
console.log("downvoted");
this.removeUserFromUpvotersList();
}
removeUserFromUpvotersList() {
this.updatedVotes.upvoters.push(localStorage.getItem('userid'));
this._articleService.removeUserFromUpvotersList(this.updatedVotes, localStorage.getItem('userid'))
.subscribe (
res => {
},
err => console.log(err)
);
}
}
article.service.ts
export class ArticleService {
...
private _deleteFromUpvotersListURL = "http://localhost:3000/api/remove-from-upvoters-list";
...
removeUserFromUpvotersList(updatedArticle, id) {
return this.http.delete<any>(this._deleteFromUpvotersListURL+'/'+id, updatedArticle);
}
}
api.ts
router.delete('/remove-from-upvoters-list/:id', (req, res) => {
console.log("removing from upvoters list");
let userId = req.params.id;
let articleId = req.body.articleid;
Article.update({ articleid: articleId }, { $pull: { upvoters: userId } }).then(opResult => console.log(opResult));
Article.deleteOne({ userId: userId }, (error, userId) => {
if (error) {
console.log(error)
} else {
if (!article) {
res.status(401).send('something went wrong')
} else {
console.log('successfully deleted');
}
}
})
})
I know my api is working fine because I'm able to perform add and update operations. Please help me with delete.
Upvotes: 0
Views: 101
Reputation: 76
In frontend you call the put method and the backend endpoint is delete. Changing to http.delete in frontend service should fix the problem.
Upvotes: 1