【问题标题】:nedb - Create databases dynamicallynedb - 动态创建数据库
【发布时间】:2021-03-23 19:53:34
【问题描述】:

我有两个 Temp.我的 Raspberry Pi 上的传感器,我有一个 node.js Express 应用程序。我想用传感器对象动态创建一个数组的 nedb 数据库。

所以我有一个带有传感器的物体:

  sensors: [
    {
      name: "Indoor",
      type: 22,
      pin: 21
    },
    {
      name: "Outdoor",
      type: 22,
      pin: 21
    }
  ]};

现在我要为每个 Sensor 三个数据库创建:

databaseSetup(app.sensors);

function databaseSetup(sensor){
  const dataStore = require('nedb');
  const databaseVariables = [];
  sensor.forEach((sensor) => {
    const live = 'live' + sensor.name;
    const seconds = 'seconds' + sensor.name;
    const hours = 'hours' + sensor.name;
    const test = { 
    live: new dataStore(`./databases/temp/${sensor.name}/live.db`),
    seconds: new dataStore(`./databases/temp/${sensor.name}/seconds.db`),
    hours: new dataStore(`./databases/temp/${sensor.name}/hours.db`) }
    databaseVariables.push(test);
  });
} 

但这不起作用。有人可以帮帮我吗?

【问题讨论】:

    标签: node.js express raspberry-pi nedb


    【解决方案1】:

    我不确定您为什么要这样做,因为在我看来这是一种不好的做法。但你可以让它动态化。像这样:

    const dt = require('nedb');
    const db = [];
    
    //USING LOOP and FUNCTION
    let list = [{ name: "GasSensor" }, { name: "TempSensor" }];
    let index = 0;
    
    //BAD Practice
    let setup = () => {
        if (index + 1 > list.length) return;
    
        let newInstance = new dt({ filename: 'nodejs/data/nedb_' + list[index].name, autoload: true });
    
        console.log("Working on index " + (index + 1));
    
        newInstance.loadDatabase((err) => {
            if (err) {
                //...
            } else {
                db.push(newInstance);
            }
    
            index++;
            setup();
        });
    }
    
    setup();
    

    还有 API:

    const exp = require("express");
    const app = exp();
    const dt = require('nedb');
    const db = [];
    
    app.get("/make/db/:name", (q, r) => {
        //BAD PRACTICE
        //JUST FOR TEST
        let newInstance = new dt({ filename: 'nodejs/data/nedb_' + q.params.name, autoload: true });
    
        newInstance.loadDatabase((err) => {
            if (err) {
                console.log(err + "");
                r.send("ERROR");
            }
            else {
                db.push(newInstance);
                console.log("Database is loaded");
                r.send("NEW DB CREATED");
            }
        });
    });
    
    app.listen(3000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2022-01-10
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多