What is the method to retrieve results using 'return' from NeDB in vue.js?

Seeking assistance on retrieving data from NeDB within a method in a .vue file using electron-vue. Currently, I am aware that the data can be stored in a variable, but my preference is to fetch it using 'return' as I intend to utilize the result in a v-for loop.

Attempts were made utilizing bluebird promisify and async/await, however, without success.

datastore.js

import Datastore from 'nedb'
import path from 'path'
import { remote } from 'electron'
export default new Datastore({
  autoload: true,
  filename: path.join(remote.app.getPath('userData'), '/data.db')
})

main.js

import db from './datastore'
Vue.prototype.$db = db

test.vue

<template>
  <div>
    <ul>
      <li v-for="member in memberName">
        {{ member.name }}({{ member.relation }}){{ member._id }}
        <ul>
          <li v-for="game in filterByName(member._id)">
            {{ game }}
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>

<script>
import Promise from 'bluebird'
export default {
  // some data
  created: function () {
    this.dbFindAsync = Promise.promisify(thistest.$db.find)
  },
  methods: {
    filterByName: async function (id) {
      const docs = await this.dbFindAsync({ 'members.nameId': id }, { 'members': 1, _id: 0 })
      console.log(docs)
      return docs
    },
  // some other methods
  }
}
</script>

An error "Uncaught (in promise) TypeError: Cannot read property 'push' of undefined" occurred.

Data retrieval from DB during creation using:

    this.$db.find({}, function (err, doc) {
      console.log(err)
      console.log(doc)
      this.list = doc || []
    }.bind(this))

In need of assistance....

Answer №1

To improve the functionality of your script, consider importing the nedb object at the beginning.

For example, you can use

const Datastore = require("nedb")
and then create a new document.

 db = new Datastore({
    filename: "a_collection_of_data",
    autoload: true,
    timestampData: true,
  });

Once you have initialized the db object, utilize it in your methods.

For instance, if you want to fetch a collection of data in the getData method, you can do something like this

getData() {
    db.find({}, function(err, doc) {
        console.log(err)
        console.log(doc)
        this.list = doc || []
    }.bind(this))
}

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

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Unable to attach child component to reference

I am currently facing an issue with VuePaginator. Despite following the documentation, I am unable to mount it to my Vue app's $refs properties. The pagination feature is working correctly, but I cannot trigger the fetchData() function from my Vue cod ...

What are the best ways to prevent JavaScript and CSS from blocking the render?

I ran my webpage through Google PageSpeed Insights and it keeps flagging an issue with render-blocking JavaScript and CSS in the above-the-fold content. The report indicates that there are 17 blocking scripts and 11 blocking CSS resources on the page. De ...

Issue: The text.replace function is not working in an AngularJS filter. What steps can be taken to resolve this?

While working in Angular, I attempted to utilize a filter to replace certain strings with different words. Despite trying numerous examples, it seems like my code is missing something crucial that I can't seem to pinpoint. Here's the snippet of m ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...

Using jQuery Mobile alongside two distinct versions of jQuery

My current task involves inserting both jQuery and custom JavaScript into the DOM of an existing page. The jQuery is inserted right before my script, where I utilize window['my$'] = jQuery.noConflict(true);. This approach worked smoothly after ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

Building a flexible table in React JS based on specific keys: a complete guide

I'm currently working on developing a dynamic table component using React JS. The component at the moment has a fixed header with the most common result keys. Some results contain additional information such as phone numbers and degrees. I'm loo ...

Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close. <div v-for="(btn, index) in dataArray"> ...

Issue with FlexSlider 2 and thumbnail slider: Previous and Next buttons not functioning for main image

I have encountered an issue while using FlexSlider 2 with the thumbnail slider. The problem is that the main image does not respond as expected. When I try to navigate using the next/prev buttons, it does not slide or fade to the next/prev image. Even cl ...

Moving between different perspectives within a single-page backbone application

I am interested in incorporating dynamic transitions similar to the ones showcased on this website into a single-page backbone application. However, I am unsure of where to begin. Do I need to modify how I initialize my views (currently using a standard sw ...

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Tips for implementing picker options to limit the starting date in the Element UI date-picker

I'm currently developing a web application using Element UI, with a specific focus on the el-date-picker component. Here is the code I have written for defining a period using two calendars. However, I am facing difficulty in applying picker-options ...

Attempting to mark fields as required with asterisks using React Final Form in a React project

Is there a way to display an asterisk next to a label on a form using React Final Form? Here is what I have tried: <Field name="requestDescription" {...(<span style={{ color: 'red' }}>*</span&g ...

AutoComplete feature activates when I choose a suggestion from the dropdown menu

<Autocomplete disablePortal id="geo-select-country" options={all_country} defaultValue={nation} onChange={(event, selected_nation) => { set_nation(selected_nation); }} ...

Customize your Angular UI Bootstrap Datepicker with unique buttons - here's how!

Currently, I have a datepicker with clear and close buttons. I tried using the append function to add more buttons to this datepicker, but it didn't work because the content is not loaded until we click the icon since it's a popup datepicker. Is ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...

I seem to be having trouble getting innerHTML to function properly

Whenever I attempt to showcase HTML code from a DIV element, the innerHTML function fails to retrieve its contents: <div id="container"> <tr> <td style="background-color: #ffffff;">TEST</td> </tr> </div> ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...