Categories
JavaScript Answers

How to get only dataValues from Node Sequelize ORM?

To get only dataValues from Node Sequelize ORM, we call the findById method.

For instance, we write

const data = await Model.findById(1);
console.log(data.get({ plain: true }));

to call findById to get the item by ID.

And then we call data.get with { plain: true } to return a plain object version of the result.

Categories
JavaScript Answers

How to get full file path in Node.js?

To get full file path in Node.js, we use the path.resolve method.

For instance, we write

const path = require("path");
const absolutePath = path.resolve("./Uploads/MyFile.csv");

to call path.resolve with a relative path to return the corresponding absolute path.

Categories
JavaScript Answers

How to convert an image to a base64-encoded data URL in sails.js or generally in the server side JavaScript?

To convert an image to a base64-encoded data URL in sails.js or generally in the server side JavaScript, we use the buffer toString method.

For instance, we write

const fs = require("fs");

const base64Encode = (file) => {
  const bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
};
const base64str = base64Encode("kitten.jpg");

to define the base64Encode function.

In it, we call readFileSync to read the file.

And then we create a Buffer with the returned file binary.

Then we call toString to convert the buffer to a base64 string.

Categories
JavaScript Answers

How to fetch/scan all items from AWS dynamodb using Node.js?

To fetch/scan all items from AWS dynamodb using Node.js, we use the scan method.

For instance, we write

const scanTable = async (tableName) => {
  const params = {
    TableName: tableName,
  };

  const scanResults = [];
  const items;
  do {
    items = await documentClient.scan(params).promise();
    items.Items.forEach((item) => scanResults.push(item));
    params.ExclusiveStartKey = items.LastEvaluatedKey;
  } while (typeof items.LastEvaluatedKey !== "undefined");

  return scanResults;
};

to call scan to scan the database.

We call promise to return a promise.

And we use await to get the results.

We use items.Items to get the items returned.

Categories
JavaScript Answers

How to use Node Sequelize findOne to find the latest entry?

To use Node Sequelize findOne to find the latest entry, we order the result by createdAt in descending order.

For instance, we write

model.findOne({
  where: { key },
  order: [["createdAt", "DESC"]],
});

to call findOne with order set to an array [["createdAt", "DESC"]] to order the result by createdAt in descending order to get the latest result.