如何将 NeDB 对象存储在集合中?

How do I store NeDB objects in a collection?

我想使用 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 实现此目的?

NeDB 存储文档,而不是 json 数据,它们只是碰巧相似。您的 json 文件将需要顶级 {} 上下文,而您的 nedb 数据库则不需要。因此,您应该将数据存储在 .db 文件中,而不是 .json 文件中,因为您没有存储 json 数据。每次插入订单时,都会插入一个新文档。您永远不会告诉 nedb 创建或推送到数组,而是插入新文档。

orders.find({}, (err, doc) => {
    console.log(doc);
})

上面的代码将 return 数组中所有插入的数据。如果我正确理解您的需求,您可以将 orders 数据视为隐式数组。您的文档不一定会按照您插入的顺序检索