Javascript 访问自己的api时无法读取未定义的属性
我正在尝试将自己的express.js api与nodejs一起使用。问题是它可以工作,但它给出了一个错误,我无法访问请愿书的结果。这是我的代码: routes.js:Javascript 访问自己的api时无法读取未定义的属性,javascript,node.js,express,Javascript,Node.js,Express,我正在尝试将自己的express.js api与nodejs一起使用。问题是它可以工作,但它给出了一个错误,我无法访问请愿书的结果。这是我的代码: routes.js: app.post('/petition/:id', function(req, res) { console.log("ID: ", req.params.id); if (!req.params.id) { return res.send({"status": "error", "message
app.post('/petition/:id', function(req, res) {
console.log("ID: ", req.params.id);
if (!req.params.id) {
return res.send({"status": "error", "message": "Chooser id needed"});
}
else {
indicoUtils.indicoPositivosNegativos(req.params.id).then(function(result) {
return res.send({"result": result});
})
}
})
calculator.js:
var indicoPositivosNegativos = function (chooserId) {
var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
Promise.all(
tweets.map(({ _id, tweet }) =>
indico.sentiment(tweet).then(result =>
TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
.then( updated => { console.log(updated); return updated })
)
)
)
)
};
我正在用Postman测试,它显示了错误:
TypeError:无法读取属性。则为未定义的
TweetModel.find创建的承诺不会从路由处理程序返回到调用函数
变量indicatopositivosnegativos=函数选择器ID{
var TweetModel=mongoose.model'Tweet'.concatchooserId,Tweet.tweetSchema;
//调用函数时需要返回承诺
//有权使用它。
返回TweetModel.find{},{
_id:1,
推特:1
}.thentweets=>
我保证
tweets.map{
_身份证,
推特
} =>
indio.mountain.tweet.thenresult=>
TweetModel.findOneAndUpdate{
_身份证
}, {
指标阳性阴性:结果
}, {
新:真的
}
.thenupdated=>{
console.logupdated;
返回更新
}
};
这基本上意味着您试图调用.then函数的对象之一未定义 具体来说,对象indicoUtils.indicoPositivosNegativosreq.params.id应该是承诺,但函数indicoPositivosNegativos不返回承诺。事实上,函数不返回任何内容,因此对未定义的值调用.then 解决方案很简单,您必须在calculator.js上添加一个return语句才能返回如下承诺:
var indicoPositivosNegativos = function (chooserId) {
var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
return TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
Promise.all(
tweets.map(({ _id, tweet }) =>
indico.sentiment(tweet).then(result =>
TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
.then( updated => { console.log(updated); return updated })
)
)
)
)
};
发现承诺从未从indicoPositivosNegativos返回。