Categories
JavaScript Answers

How to populate a sub-document in Node Mongoose after creating it?

To populate a sub-document in Node Mongoose after creating it, we call the populate method.

For instance, we write

Item.find({})
  .populate("comments.created_by")
  .exec((err, items) => {
    console.log(items[0].comments[0].created_by.name);
  });

to call find to get the items from Items.

And we call populate to get the data for the comments.created_by field for each entry.

Then we call exec to return the results as a plain array.

We get the results from the items array.

Categories
JavaScript Answers

How to write to a CSV in Node.js?

To write to a CSV in Node.js, we call writeFile.

For instance, we write

let dataToWrite;
const fs = require("fs");

fs.writeFile("form-tracking/formList.csv", dataToWrite, "utf8", (err) => {
  if (err) {
    console.log("Some error occured");
  } else {
    console.log("It's saved!");
  }
});

to call writeFile to write the dataToWrite CSV string to the form-tracking/formList.csv file.

If there’re any errors then, err in the callback would be set.

Categories
JavaScript Answers

How to add wildcard mapping in entry of Node Webpack?

To add wildcard mapping in entry of Node Webpack, we use glob.

For instance, we write

const glob = require("glob");
// ...
module.exports = {
  //..
  entry: glob.sync("./src/scripts/*.js"),
};

to set entry to the pattern returned by glob.sync to add all the paths that match the pattern as entry points.

Categories
JavaScript Answers

How to set JWT token expiry time to maximum in Node?

To set JWT token expiry time to maximum in Node, we call the sign method.

For instance, we write

const token = jwt.sign({ email_id: "123@gmail.com" }, "secret", {});

to call jwt.sign to create a token with the object as the data and the 'secret' secret.

We leave out the expiry time value to set the expiry time to the maximum value.

Categories
JavaScript Answers

How to save array of strings with Node Mongoose?

To save array of strings with Node Mongoose, we put the data type in an array.

For instance, we write

const personSchema = new mongoose.Schema({
  tags: [
    {
      type: String,
    },
  ],
});

to add the tags field to the personSchema and make it a string array field with

[
  {
    type: String,
  },
];