I am currently using Node.js, Express.js, and MongoDB to create a basic REST API. I am trying to redirect to another page after executing a query but my console is throwing the error in the title. Here is my code:
app.post('/', (req, res) => {
MongoClient.connect(process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
const dbo = db.db("mydb");
const messageTable = dbo.collection("messages");
let myobj = { message: req.body.message };
console.log(myobj)
messageTable.insertOne(myobj, function (err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
//Get message
MongoClient.connect(process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
const messageTable = db.db('mydb').collection('messages');
var myPromise = () => {
return new Promise((resolve, reject) => {
messageTable.aggregate(
[{ $sample: { size: 1 } }]
).toArray((err, data) => {
err
? reject(err)
: resolve(data[0]);
});
});
}
//Step 2: async promise handler
var callMyPromise = async () => {
var result = await (myPromise());
//anything here is executed after result is resolved
return result;
};
//Step 3: make the call
callMyPromise().then(function (result) {
db.close();
res.json(result);
res.redirect('/');
});
});
}); //end mongo client
The code only throws errors when I include the res.redirect('/');
.
Also I do not know if this has anything to do with it but here is my get request:
app.get('/', (req, res) => {
fs.readFile('./views/home.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});