我正在使用Nodejs和cloud firestore作为数据库,我从模型中的数据库(注销)中获取了正确的数据,但是将其返回到控制器后我却无法获得它
// this is controller:
CheckPhoneNumber = (req, res) => {
// getting data from json
var json = {
// this is the entry ==> PhoneNumber : 123456789
PhoneNumber: req.body.PhoneNumber
}
// calling model function
console.log('this is from controller before calling database');
var user = model.CheckPhoneNumber(json.PhoneNumber)
.then(function () {
console.log('this is from controller after calling database');
console.log(user);
return user;
}).catch(err => {
return 'Error in controller awaiting ', err;
});
// outputting to Postman
return res.json(Promise.resolve(user));
}
该控制器调用以下模型
// this is model :
// importing configure of database
const config = require('../config/main');
// this is for updates from google to firestore
config.db.settings({ timestampsInSnapshots: true });
// setting root of users database
const usersRoot = config.db.collection( my root here );
// takes json and return that user which phone number belongs to (actually it gets user by phone number )
async function CheckPhoneNumber(PhoneNumber) {
// getting data from database
var user;
user = await usersRoot.where('PhoneNumber', '==', PhoneNumber).get()
.then(async snapshot => {
if (snapshot.empty) {
return 'No matching documents.';
}
return await snapshot.forEach(async doc => {
console.log('your user is : ');
user = await doc.data();
console.log(user);
console.log('this is from model after calling database');
return await user;
});
}).catch(err => {
// console.log('Error getting documents',err);
return 'Error getting documents', err;
});
console.log('this is user befor returning : ');
console.log(user);
return user;
}
这是Windows OS中控制台的输出
this is from controller before calling database
this is from model after calling database
{ ... there is here some data ... }
this is from controller after calling database
Promise { <'pending'> }
我希望在等待它从控制台的最后一行中的数据库中获取数据后,特别是从控制器返回的数据
答案 0 :(得分:0)
这是因为您的user
是promise
对象。
您可能想在此区块中进行回复,
model.CheckPhoneNumber(json.PhoneNumber)
.then(function (user) {
console.log('this is from controller after calling database');
console.log(user);
res.json(user)
})
.catch(err => {
res.json('error')
});
或者,您可以这样做:
// make you route function async
CheckPhoneNumber = async (req, res) => {
...
// then you could
try {
const user = await model.CheckPhoneNumber(json.PhoneNumber)
res.json(user)
} catch (e) {
res.json('error')
}
将模型更改为:
async function CheckPhoneNumber(PhoneNumber) {
// getting data from database
try {
var snapshot = await usersRoot.where('PhoneNumber', '==', PhoneNumber).get()
if (snapshot.empty)
return "No"
var datas = [];
snapshot.forEach(doc => {
datas.push(doc.data())
})
return datas;
} catch (e) {
console.error(e);
}
}