To remove all properties from a object with Node.js, we assign the variable to an empty object.
For instance, we write
req.session = {};
to assign req.session to an empty object to remove all properties from it.
To remove all properties from a object with Node.js, we assign the variable to an empty object.
For instance, we write
req.session = {};
to assign req.session to an empty object to remove all properties from it.
To fix "Error: Cannot find module ‘ejs’ " with Node.js, we install the ejs library.
To install it, we run
npm install ejs
in our project folder to install the ejs package with npm.
To define an array as an environment variable in Node.js, we can define it as a JSON array.
For instance, we write
ANY_LIST = ["A", "B", "C"]
to add the ANY_LIST environment variable to our .env file.
Then we write
const LIST = JSON.parse(process.env.ANY_LIST);
to get the ANY_LIST environment variable with process.env.ANY_LIST.
And we parse it into an array with JSON.parse.
To create document if not exists, otherwise, update and return document in either case with Node.js Mongoose, we call the findOneAndUpdate method.
For instance, we write
const query = {};
const update = { expire: new Date() };
const options = { upsert: true, new: true, setDefaultsOnInsert: true };
Model.findOneAndUpdate(query, update, options, (error, result) => {
if (error) return;
//...
});
to call findOneAndUpdate with the query and the update object that has the values to update in the documents.
And then the updated document are set as the value of the result parameter.
To fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js, we make sure we only return a response once.
For instance, we write
if (!user) {
errors.email = "User not found";
res.status(404).json({ errors });
return;
}
to call res.status and json to return the 404 status and the { errors } as the response body to send the response.
Then we use return to stop running the function to make sure another response isn’t sent.