[英]Why find() method doesn't show the recent data from mongoDb database in Express.Js
When the app.post('/form-submit', funtion(req, res))
method is called then i am expecting it to first save the data using save()
, which it did fine but then i call find()
method which shows all the data from mongoDB database except the current data that is recently added by save()
method.当app.post('/form-submit', funtion(req, res))
方法被调用时,我希望它首先使用save()
保存数据,它做得很好,但后来我调用find()
方法它显示了 mongoDB 数据库中的所有数据,除了最近通过save()
方法添加的当前数据。
I want that find()
method show the current data as well .我希望find()
方法也显示当前数据。 But show()
method only shows previous data not recent one.但是show()
方法只显示以前的数据而不是最近的数据。 And i thing maybe it is Asynchronous problem我的事情可能是异步问题
//For Put request in index.js
app.post('/form-submit', function(req, res) {
//To add the current data into database
connect.then((db) => {
var newTask = taskSchema({
Task: req.body.Task
});
newTask.save();
});
//To show the data into page 'showTask.ejs
taskSchema.find({}, function(err, val) {
console.log(res.length);
res.render('showTask.ejs', { todoTask: val });
});
});
save is async保存是异步的
it can either return a promise or take a callback (err) => {}它可以返回 promise 或进行回调 (err) => {}
so you fetch information at the time it didn't manage to save yet所以你在它还没有设法保存的时候获取信息
app.post('/form-submit', function(req, res) {
//To add the current data into database
connect.then((db) => {
var newTask = taskSchema({
Task: req.body.Task
});
return newTask.save();
}).then(() => {
//To show the data into page 'showTask.ejs
taskSchema.find({}, function(err, val) {
console.log(res.length);
res.render('showTask.ejs', { todoTask: val });
});
});
});
or:或者:
app.post('/form-submit', async function(req, res) {
//To add the current data into database
const db = await connect;
var newTask = taskSchema({
Task: req.body.Task
});
await newTask.save();
//To show the data into page 'showTask.ejs
taskSchema.find({}, function(err, val) {
console.log(res.length);
res.render('showTask.ejs', { todoTask: val });
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.