Greetings, I am currently experimenting with an express app that utilizes a typicode/lowdb json file as its database. However, I am encountering difficulties with getting the update function to work properly. Below is an example of the code:
The typicode/lowdb db.json
{
"posts": [
{
"name": "first post",
"desc": "first desc",
"slug": "first-post",
"id": "uuid.v4()"
},
{
"name": "second post",
"desc": "second desc",
"slug": "second-post",
"id": "uuid.v4()"
}
]
}
Code snippet for create/update/delete.js
var uuid = require('node-uuid');
var low = require('lowdb');
var storage = require('lowdb/file-async');
var db = low('./database/db.json',{ storage: storage });
var add = function (item) {
var id = uuid.v4();
item.id = id;
db('posts').push(item);
};
var getById = function (id) {
return db('posts').find({ id: id});
};
var update = function (item,id) {
item.id = id;
db('posts').chain().find({ id: id}).assign(item).value();
//The issue arises here where the db.json file does not get updated
//Upon console log, this is the result from the update function:
{
"name": "first post edited",
"desc": "first desc edited",
"slug": "first-post-edited",
"id": "undifined"
}
console.log(db('posts').chain().find({ id: id}).assign(item).value());
};
Example of handle-the-update.js
exports.update = router.post('/update',function (req, res) {
db.update({name:req.body.name,desc:req.body.desc,slug:slug,id:req.params.id});
res.redirect('/post');
});
The functions for creating, deleting, and fetching posts by ID are working correctly, except for the update functionality. Any insights on why this might be happening? I have tried using .filter(), .where() but none seem to work in updating the db.json file.