简体   繁体   中英

How do I store NeDB objects in a collection?

I want to use NeDB as a database for a very simple ExpressJS application. I would like to store collections of objects into a separate file, so one file for orders (orders.json). However, whenever I insert an order object into the datastore, it is just appended as an extra object instead of creating an array.

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);

This stores the objects as:

{"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"}

As you might see already, this is invalid JSON. I expect them to be stored in an array (one array containing all orders).

How can I achieve this using NeDB?

NeDB stores documents, not json data, they just happend to be similar. Your json files will need a top level {} context, while your nedb database wont. You should therfore store the data in .db files, not .json files, as you are not storing json data. Each time you are inserting order, you are inserting a new document. You are never telling nedb to create or to push to an array, instead you are inserting new documents.

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

The code above will return all your inserted data in an array. If I understand your needs correctly, you could think of the orders data as an implicit array. Your documents will not necessarily be retrived in the same order as you inserted them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM