Search code examples
javascriptarraysnode.jsnedb

How to use variable as dot notation address in node.js with Nedb? TypeError 'cannot read property 'find' of undefined


So I'm trying to create a forum in multiple languages using Nedb as the base database (for the time being). I want to pass the variable 'language', into the 'dot notation' address. Is this possible?

const Datastore = require('nedb');

const db = {};
 db.forum = new Datastore('forum.db');
 db.forum_de = new Datastore('de_forum.db');

 db.forum.findOne({ "TYPE": req_TYPE, "forum_UID":req_ID }, function (err, docsT) {
     if(docsT !== null) {
      var s_lan = docsT.USER_LEARN_LAN 
     s_lan = '_' + s_lan



  db.forum+s_lan.find({ $or: [{ "PARENT_ID": req_ID }, { 'GRAND_PARENT_ID': req_ID }] }, async 
   function (err, docs) {
      if(docs.length !== 0 ){

So the thread of interest to the user is located in db.forum the result of this search reveals the user's language, "s_lan". I want to then use this result to search the Datastor db.forum_de.

How do you include a variable in the dot notation address to the datastore?


Solution

  • In order to access/set a field of an object using a variable/dynamically you need to use the [] syntax. For the example given we would have something like the below if you are using es6 and above.

    let langKey = `forum_${s_lan}`
    db[langKey].find()