Tips for Updating an item array in typicode/lowdb file database

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.

Answer №1

Experiencing the same issue today. It's possible that there have been changes to the lowDB Readme on GitHub since your initial question, as it now seems to be functioning as expected.

Below is an example of how you can adjust your code:

const low = require('lowdb');
const fileAsync = require('lowdb/file-async');
const db = low('./database/db.json',{ storage: fileAsync });
const postStore = db.get('posts');

postStore.find({ id: "uuid.v4()" })
   .assign({name: "new name"})
   .value();

I have tested this solution today and confirm that it should work properly.

Updating both records in your examples because they share the same id.

Answer №2

In order to follow the lowdb guide correctly, make sure to use the write() method instead of assign() when updating a specific item in the database:

db('posts').chain().find({ id: id}).assign(item).write();

Answer №3

const lowDb = require('lowdb');
const database = lowDb('posts.json')

database.defaults({ posts: [], user: {} })
  .value()

database.get('posts')
  .push({ id: 1, title: 'lowdb is amazing'})
  .value()

database.set('user.name', 'coder123')
  .value()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...

Is it practical to use JSON.parse for processing large datasets exceeding 50 megabytes in size?

When developing my android app, I initially used Firebase for real-time data storage. However, due to the high pricing, I made the decision to switch over to a NodeJS server. Since I am new to NodeJS... The Firebase real-time database stores data in JSON ...

Utilizing JavaScript or jQuery in MVC4 to showcase information for the primary record

I'm currently working on constructing a page that displays a list of users. My aim is to have a "Details" link in each row that, when clicked, will render a partial view on the same page without having to reload it using either javascript or jQuery. D ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

Vue-router: the browser tries to open a <router-link> element as if it were a local file

Having some trouble with Vue-router - when I click on a navigation link, the desired component briefly displays before the browser tries to open it as a file. For instance, clicking on the "Badger!" link results in the browser attempting to open a local f ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Logging in Python: A Guide to JSON Formatting

Our Python Django application requires logging using the code snippet below in order to allow ELK to index the log record as JSON logger.info(json.dumps({'level':'INFO','data':'some random data'}) We currently have ...

Issues with req.params not getting invoked in Express.js

After hours of contemplation, I'm still struggling to figure out the issue at hand. Let's start with how I defined a route: var home = require('./routes/home'); var app = express(); app.use('/home/:client', home); The code ...

Using knockoutjs to call a component on the home page

I am currently facing some challenges with knockoutjs components, as I am following the guidance provided in the official knockout component documentation. Could someone please advise me on how to correctly invoke my widget component on the main page? It ...

Tips for automatically inserting a "read more" link once text exceeds a certain character count

Currently utilizing an open-source code to fetch Google reviews, but facing an issue with long reviews. They are messing up the layout of my site. I need to limit the characters displayed for each review and provide an option for users to read the full rev ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

I'm currently working on incorporating an edit feature into the create form by utilizing server actions in the latest version of Next.js, version 14

The issue arises when the create form's type (id) parameter is null, which does not align with prisma's (edit info). export function AboutForm({ id }: { id: number }) { const router = useRouter(); const [err, setErr] = useState("&qu ...

Mysterious Node.js 504 errors

Our server setup includes Node (v0.10.38) with Express (4.0.0), and nginx (1.2.1) as a proxy, which has been functioning well for the most part. Recently, we made changes to our server configuration and encountered a problem. Approximately 30 minutes after ...

What is the mechanism of interaction between sessions in PassportJS?

I've been struggling to grasp the login and signup process in PassportJS and ExpressJS. My goal is to test whether multiple sessions are being generated. To do this, I set up a server and opened two browser windows, each on the login page. After loggi ...

JSONP error: "Syntax error - token not expected"

While attempting to perform a JSONP AJAX request, an error was thrown: Uncaught SyntaxError: Unexpected token I'm puzzled about what is wrong in my code. Can someone assist? $.ajax({ url: 'http://api.server32.trustklik.com/apiv1/website/ ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

Error: The callback specified is not a valid function

Here is a function example: reportAdminActions.reportMemberList(project, function(data) { console.log(data); }); This particular function gets called by another ajax operation, similar to the one shown below: reportMemberList: function(projectId, ca ...

Is there a way to customize a package.json file using postinstall?

I've developed a package on npm that generates an "scss directory structure" and my goal is to include custom scripts in the package.json file located at the project's root. MY-PROJECT ├── node_modules ├── scss └── package.json ...