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

"Addressing the Issue of Memory Leakage in Node.js File Upload

Currently, I am developing an API using Node.js and Express. The issue I am facing is that when a user uploads a file, the server modifies it using the sharp image processing library and then uploads it to a Google Cloud Storage bucket. Strangely, the RAM ...

What is the best way to create custom middleware in Express to promptly respond with a 413 status code if the incoming request exceeds a

It seems that the current setup is not returning any response. What's strange is that the debug logger indicates POST /ServiceName 413 2ms var maxSize = 1000*1000; module.exports = function (req, res, next) { var size = req.headers['content-l ...

Warning in Vue 3: Production is being disrupted by "tags with side effects"

After recently upgrading from Vue 2 to Vue 3, I encountered a problem in my app where certain parts show a warning in development mode: [Vue warn]: Template compilation error: Tags with side effect (<script> and <style>) are ignored in client ...

Tips for preventing duplicate primary keys and values when interacting with a PHP MySQL database

Can you please review my code below? I am encountering an issue where when I insert values into the actor and movie tables, I get different primary keys but with the same values. My intention is to group all the same values under one primary key (e.g., &ap ...

Mastering Anchors in AngularStrap ScrollSpy

Is there a way to effectively utilize AngularStrap's ScrollSpy feature to link to anchors within the same document? Upon reviewing the AngularStrap documentation, I noticed that when a link is clicked, a double hash is generated in the URL. For examp ...

Is there a way to automatically redirect my page after clicking the submit button?

I'm having trouble with the code below. I want it to redirect to NHGSignin.php if 'new horizon gurukul' is entered. When I click the Next button, it's supposed to take me there but it's not working as expected. Can anyone help me f ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Prevented: Techniques for providing extra cushioning for a button, but with the condition that it contains an external icon

How can I apply padding to a button only if it contains an external icon? If the button has an external icon, I want to give it padding-right: 30px (example). However, if there is no external icon present, then the button should not have the 30px padding. ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Adjusting the size of <nav> element to accommodate its child elements

I've exhausted all possible CSS solutions today in an attempt to make my parent nav tag home-main-nav-menu resize based on its children and grandchildren, but it just won't cooperate. If anyone could provide a clear explanation on how to solve th ...

Integration of Lex Bot with REST API

Could someone help me figure out how to connect my Lex bot with my REST API project so I can retrieve pricing information for my products? The endpoint to get pricing is already set up in my project as a REST method with JSON request and response. I'v ...

The display/block feature will only function if the div element is contained within a table

I am facing an issue with hiding/showing two div elements alternatively. The code works perfectly when the divs are placed within a table, but fails when they are not in a table due to compatibility issues with Internet Explorer. I prefer not to use a tabl ...

What is the layout of JqueryMobile web pages like?

When I need to pull pages, I use Asp.net MVC. The format of my pages is as follows: { Layout = ""; } <div data-role="page"> .... <script type="text/javascript"> $(document).one("pageinit", function () { . ...

Remove an item from Firebase using React with ES6 syntax

[HELP NEEDED]Seeking solution below Encountering an issue with deleting an object from the Firebase database. I have experience with this, but for some reason it's not functioning as expected: Action: export const firebase_db = firebase.database(). ...

Error message: When trying to use express session with Socket.IO, the response from the

Currently, I am working on implementing session management using express 4.x and socket io 1.4, while following guidance from this referenced answer. However, I have encountered an issue where the second argument to the express session function is returnin ...

AngularJS, building a hash of resources

Is there a way, in an AngularJS controller, to take a URL and redirect that request to the best place for fetching JSON data? The VideoSearchCtrl is connected to the search form. Everything seems fine with the generated URL for the template, so I aim to us ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

A guide on how to successfully send multiple arguments to a single Javascript method by utilizing thymeleaf onclick (th:onclick) functionality

I attempted to use the code below, but unfortunately it did not work as expected. Can you please provide me with a solution? Javascript Code ---> function passValue(id, name){ console.log(id) console.log(name) document.getE ...

Error in ExpressJS regarding CORS: The requested resource does not include the necessary 'Access-Control-Allow-Origin' header

After conducting thorough research, I am confident that my config is set up correctly and there should be no issues with CORS. However, when attempting to make a POST request using axios from localhost:3000 to my API on localhost:8000, I encountered the fo ...