Reputation: 181
I'm new to Express and databases. I'm trying to create a simple CRUD todo list by following several tutorials using Mongo DB (not Mongoose), Express, Node, and Handlebars.
I can create items from an input form and have them successfully save to the Mongo database and the page. I can't figure out how to delete each item based on a button click both on the page and from the database. Ideally, I want to target them based on the _id
that Mongo creates.
I think the issue might be having something to do with the way I'm trying to select each item. Any suggestions or easier ways to implement this would be great!
Here is my code for Express:
// Connecting Mongo DB
MongoClient.connect(url, (err, client) => {
if (err) return console.log(err)
db = client.db('todoitems')
})
// Save items to DB from form
app.post('/items', (req, res) => {
db.collection('items').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body, {_id: req.body._id})
res.redirect('/')
})
})
// Delete item on click from DB
app.delete('/items/:id', (req, res) => {
db.collection('items').remove({_id: req.body.id}, (err, result) => {
if (err) return console.log(err)
console.log(req.body)
res.redirect('/')
})
})
// Get items from DB to page
app.get('/', (req, res) => {
db.collection('items').find().toArray((err, result) => {
if (err) return console.log(err)
res.render('index', {
layout: false,
items: result
});
})
})
And here is my code from the Handlebars file:
<form action="/items" method="POST">
<input type="text" placeholder="item" name="item">
<input type="hidden" id="date" name="date" value="CurrentDate">
</form>
<ul>
{{#each items}}
<li>
<span>{{item}} |</span>
<span>{{date}}</span>
<button id={{_id}}>x</button>
</li>
{{/each}}
</ul>
Upvotes: 1
Views: 6525
Reputation: 2654
If you are removing by _id
, you need to pass an ObjectID(id)
not a "string" id
, something like:
remove({_id: mongodb.ObjectID( req.params.id)} ...
So, your code should be like:
app.delete('/items/:id', (req, res) => {
db.collection('items').remove({_id: mongodb.ObjectID( req.params.id)}, (err, result) => {
if (err) return console.log(err)
console.log(req.body)
res.redirect('/')
})
})
Upvotes: 3