Search code examples
javascriptnode.jsexpressnedb

How to store only certain fields from NeDB database into an array with NodeJS


I have an embedded NeDB database with numerous entries with multiple fields and I'm looking to only get the dates from every entry and store it into an array. I'm using NeDB, NodeJS and express.

The dataset looks like so:

{"goalName":"swim 5km","details":"I want to swim 5km","date":"2021-05-15","completed":false,"author":"somename","_id":"BMnvTm54rNbwc9D4"}
{"goalName":"swim 5km","details":" I want to swim another 5km","date":"2021-03-14","completed":false,"author":"somename","_id":"EwEicEYZAfFxY9Z6"}
{"goalName":"20 pushups","details":"I want to complete 20 full pushups","date":"2021-05-14","completed":false,"author":"anthername","_id":"rP7q6L8jnwGyAgGD"}

I'm only interested in the dates where the author is somename,

I can retrieve these documents using:

getEntriesByUser(userName) {
  return new Promise((resolve, reject) => {
    this.db.find({ 'author': userName }, function (err, entries) {
      if (err) {
        reject(err);
      } else {
        resolve(entries);
        console.log('getEntriesByUser returns: ', entries);
      }
    })
  })
}

which then returns the documents where the username = someusername, but i'm only interested in the dates. Preferably storing them to an array with a result like so:

[2021-05-15, 2021-03-14, 2021-05-14]

How would I got about doing this?

Thanks for your help!


Solution

  • You can use the optional second projection parameter of the find() and findOne() methods to include or omit properties of the returned records. see: NeDB#projections.

    db.find({ author: userName }, { date: 1, _id: 0 }, function (err, docs) {...});
    

    const
      Datastore = Nedb,
      db = new Datastore(),
      data = [
        { goalName: "swim 5km", details: "I want to swim 5km", date: "2021-05-15", completed: false, author: "somename" },
        { goalName: "swim 5km", details: " I want to swim another 5km", date: "2021-03-14", completed: false, author: "somename" },
        { goalName: "20 pushups", details: "I want to complete 20 full pushups", date: "2021-05-14", completed: false, author: "anthername" },
      ];
    
    for (const datum of data) {
      db.insert(datum);
    }
    
    function getEntriesByUser(userName) {
      return new Promise((resolve, reject) => {
        db.find({ author: userName }, { date: 1, _id: 0 }, function (err, entries) {
          if (err) {
            reject(err);
          } else {
            resolve(entries);
            console.log('getEntriesByUser returns: ', entries);
          }
        })
      })
    }
    
    getEntriesByUser('somename').then((entries) => {
      console.log('Mapped return value: ', entries.map(({ date }) => date));
    });
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/nedb/1.8.0/nedb.min.js"></script>