Categories
JavaScript Answers

How to convert a string to Object Id in Node.js MongoDB native driver?

Sometimes, we want to convert a string to Object Id in Node.js MongoDB native driver.

In this article, we’ll look at how to convert a string to Object Id in Node.js MongoDB native driver.

How to convert a string to Object Id in Node.js MongoDB native driver?

To convert a string to Object Id in Node.js MongoDB native driver, we can use the ObjectId function.

For instance, we write

const {
  ObjectId
} = require('mongodb');

const y = ObjectId("507f191e810c19729de860ea")

to convert the string '507f191e810c19729de860ea' to an MongoDB object ID with ObjectId and assign it to y.

Conclusion

To convert a string to Object Id in Node.js MongoDB native driver, we can use the ObjectId function.

Categories
JavaScript Answers

How to force SSL and HTTPS in Express.js?

Sometimes, we want to force SSL and HTTPS in Express.js.

In this article, we’ll look at how to force SSL and HTTPS in Express.js.

How to force SSL and HTTPS in Express.js?

To force SSL and HTTPS in Express.js, we can call res.redirect to redirect to the HTTPS URL if the request wasn’t made with HTTPS.

For instance, we write

const requireHTTPS = (req, res, next) => {
  if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {
    return res.redirect(`https://${req.get('host')}${req.url}`);
  }
  next();
}

to define the requireHTTPS middleware to check if a secure request isn’t made with

!req.secure && req.get('x-forwarded-proto') !== 'https'

And we check if the environment the app is running in isn’t development with

process.env.NODE_ENV !== "development"

If they’re both true, then we call res.redirect to redirect to the HTTPS URL.

Otherwise, we call next to call the next middleware.

Conclusion

To force SSL and HTTPS in Express.js, we can call res.redirect to redirect to the HTTPS URL if the request wasn’t made with HTTPS.

Categories
JavaScript Answers

How to find and update a subdocument with Mongoose?

Sometimes, we want to find and update a subdocument with Mongoose.

In this article, we’ll look at how to find and update a subdocument with Mongoose.

How to find and update a subdocument with Mongoose?

To find and update a subdocument with Mongoose, we call findOneAndUpdate with the $set operator.

For instance, we write

Folder.findOneAndUpdate({
    "_id": folderId,
    "permissions._id": permission._id
  }, {
    "$set": {
      "permissions.$": permission
    }
  },
  (err, doc) => {

  }
);

to call findOneAndUpdate with an object with the $set property.

We use it to set the permissions array to permission by setting $set to

{
  "permissions.$": permission
}

Conclusion

To find and update a subdocument with Mongoose, we call findOneAndUpdate with the $set operator.

Categories
JavaScript Answers

How to delete a folder on S3 with Node.js?

Sometimes, we want to delete a folder on S3 with Node.js.

In this article, we’ll look at how to delete a folder on S3 with Node.js.

How to delete a folder on S3 with Node.js?

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.

For instance, we write

const emptyS3Directory = async (bucket, dir) => {
  const listParams = {
    Bucket: bucket,
    Prefix: dir
  };
  const listedObjects = await s3.listObjectsV2(listParams).promise();

  if (listedObjects.Contents.length === 0) {
    return;
  }

  const deleteParams = {
    Bucket: bucket,
    Delete: {
      Objects: []
    }
  };

  deleteParams.Delete.Objects = listedObjects.Contents.map(({
    Key
  }) => Key);
  await s3.deleteObjects(deleteParams).promise();
  if (listedObjects.IsTruncated) {
    await emptyS3Directory(bucket, dir);
  }
}

to define the emptyS3Directory that calls listObjectsV2 and promise to return a promise that returns all the file data in the bucket.

Then we define the deleteParams with the Delete.Objects property that we populate with

deleteParams.Delete.Objects = listedObjects.Contents.map(({
  Key
}) => Key);

to fill it with the keys to remove from the bucket.

And then we remove all the bucket contents with

await s3.deleteObjects(deleteParams).promise();

Finally, we check if the bucket is empty with listedObjects.IsTruncated.

And then we empty the bucket with

await emptyS3Directory(bucket, dir);

Conclusion

To delete a folder on S3 with Node.js, we can use listObjectsV2 to list all objects in a bucket.

Then we call deleteObjects to delete the objects in the document.

Categories
JavaScript Answers

How to wait for async actions inside AWS Lambda?

Sometimes, we want to wait for async actions inside AWS Lambda.

In this article, we’ll look at how to wait for async actions inside AWS Lambda.

How to wait for async actions inside AWS Lambda?

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.

For instance, we write

exports.handler = async (event) => {
  const uploadPromises = folder.files.map(file => {
    return s3.putObject({
      Bucket: "mybucket",
      Key: file.name,
      Body: file.data
    }).promise();
  });

  await Promise.all(uploadPromises);
  return 'exiting'
};

to call folder.files.map with a callback to return the promise returned by promise after calling putObject.

Then we call Promise.all with uploadPromises to run all the promises in parallel and wait for all of them to be done with await before running the return statement.

Conclusion

To wait for async actions inside AWS Lambda, we can return a promise from method that does async actions.

Then we can use await to wait for the action to complete.