首页 > 解决方案 > 如何将 NeDB 对象存储在集合中?

问题描述

我想使用 NeDB 作为一个非常简单的 ExpressJS 应用程序的数据库。我想将对象集合存储到一个单独的文件中,所以一个文件用于订单(orders.json)。但是,每当我将订单对象插入数据存储区时,它只是作为一个额外的对象附加,而不是创建一个数组。

var Datastore = require('nedb')
  , orders = new Datastore({ filename: __dirname + '/orders.json', autoload: true });

  const order = {
    chatId: 4324234,
    url: 'https://google.com',
    maxPrice: 200,
    incrementPrice: 2,
    expiryHours: 24,
    timestamp: Date.now()
  }

  orders.insert(order);
  orders.insert(order);

这将对象存储为:

{"chatId":1,"url":"https://google.com","maxPrice":200,"incrementPrice":2,"expiryHours":24,"timestamp":1631185683197,"_id":"mh9tdb06Tw29JXSW"}
{"chatId":1,"url":"https://google.com","maxPrice":200,"incrementPrice":2,"expiryHours":24,"timestamp":1631185691156,"_id":"8Dg6GXFlygYMPmRZ"}

正如您可能已经看到的,这是无效的 JSON。我希望它们存储在一个数组中(一个包含所有订单的数组)。

如何使用 NeDB 实现这一目标?

标签: javascriptnode.jsexpressnedb

解决方案


推荐阅读