skip to Main Content

I add object with categories in a DB. It shows the price and date of addition. How can I print the date to the console? Now, I have in the console: [ [ { cost: ’50$’, date: [Object] } ] ]. And I need to take what is in date. How can i do this?

// my obj

сategories: {
    products: {
      cost: "50$",
      date: {
        day: `11`,
        month: `11`,
        year: `11`,
      },
    },
  },

  // get date

  mongoClient.connect(function(err, client) {
    const db = client.db("expensesdb");
    const collection = db.collection("users");

    if (err) return console.log(err);

    collection.find({
      name: "Tom"
    }).toArray(function(err, results) {
      let res = results.map((user) => user.сategories.map((cat) => cat.products));
      console.log(res);
      client.close();
    });
  });

2

Answers


  1. For printing all json data use:

    console.log(JSON.stringify(res, null, 2));
    

    It serializes your res variable with 2 indent spaces, so it basically turn your JavaScript object into a Json string equivalent.

    null refer to a replacer function.

    See details on documentation.

    Login or Signup to reply.
  2.         let Object = {
                сategories: {
                    products: {
                    cost: "50$",
                        date: {
                            day: `11`,
                            month: `11`,
                            year: `11`,
                        },
                    },
                }
            }
    
            let DateObject = Object.сategories.products.date
            let Date = `${DateObject.year} / ${DateObject.month} / ${DateObject.day}`
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search