Like any kind of apps, there are difficult issues to solve when we write Node apps.
In this article, we’ll look at some solutions to common problems when writing Node apps.
Get the _id of Inserted Document in Mongo Database in NodeJS
We can get the _id
of the inserted document in the Mongo database from the callback that’s called by the insert
method.
For instance, we can write:
collection.insert(obj, (err, docsInserted) =>{
console.log(docsInserted);
});
We pass in the obj
to the collection
.
Then we get the docsInserted
parameter’s value to get the whole object including the ID with the _id
.
Notify Node App when Data Values Change in Redis
We can use the Redis client for Node to watch for data value changes.
For instance, we can write:
const redis = require("redis");
const client = redis.createClient();
client.subscribe("pubsub");
client.on("message", (channel, message) => {
console.log(channel, message);
});
We just call createClient
to create a Redis client instance.
Then we subscribe to to the pubsub
action to listen to published changes.
Finally, we listen to the 'message'
event to get the messages.
Delete Query with Sequelize.js
We can make a delete query with Sequelize by writing:
Model.destroy({
where: {
id: 123
}
})
where Model
is the model class of the data table that has the entry we want to remove.
Then we call destroy
to delete the entry.
where
has the where. id
is the ID field.
It can be replaced with other criteria.
Make Express.js App Work on a Different Port
We don’t have to hard code the port that the Express app listens to.
Instead, we can read the value from an environment variable.
For instance, we can write:
app.js
const express = require("express");
const app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', (req, res) => {
res.send('hello world');
});
app.listen(app.get('port'));
Then we get the port from the environment variables instead of hard-coding the port.
process.env.PORT
is the value of the PORT
environment variable.
Now we can set the port and run our app at the same time by running:
PORT=8080 node app.js
Connect to a Postgres Database with the Node Postgres Module
To connect to a Postgres database with the Node Postgres module, we can use the pg.connect
method.
For instance, we can write:
module.exports = {
query(text, values, cb) {
pg.connect((err, client, done) => {
client.query(text, values, (err, result) => {
done();
cb(err, result);
})
});
}
}
We make use of the pg.connect
method to connect to the database.
Then we use the client
object, which is the database client object, to make a query.
text
has the parameterized query.
values
has the values for the query.
The callback is called when the query is finished.
result
has the results.
We call our cb
callback so that the results can be obtained when we call the query
method.
Using socket.io in Express 4 and express-generator’s /bin/www
We can use socket.io by adding the io
object to the app.js
file:
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const io = socketIo();
app.io = io;
io.on("connection", ( socket ) => {
console.log('connected');
});
module.exports = app;
We attach the io
object as the property of app
.
We listen to the 'connection'
event with the on
method.
Then we can use it by writing the following in bin/www
:
//...
const server = http.createServer(app);
const io = app.io;
io.attach(server);
We import the app
object before calling createServer
and then call io.attach
to attach the socket.io listeners to the Express app.
Then in our route file, we can write:
const app = require('express');
module.exports = (io) => {
const router = app.Router();
io.on('connection', (socket) => {
//...
});
return router;
}
Then we change app.js
to:
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const io = socketIo();
app.io = io;
io.on("connection", ( socket ) => {
console.log('connected');
});
const routes = require('./routes/index')(io);
//...
module.exports = app;
Conclusion
We can get the ID of the inserted MongoDB document from the insert
callback.
We can incorporate socket.io into the Express app generated by the express-generator by attaching the io
object to the app
.
Also, we can use the Postgres database with Node apps by connecting to the database and using the client object returned after creating the connection.