我有一个带有find
的include
查询,以获取指针数据。它工作正常,但是如果指针对象不存在,则服务器崩溃。
这是我的查询:
var repliesQuery = new Parse.Query("Reply");
repliesQuery.include("author");
repliesQuery.find({
useMasterKey: true
}).then(function(foundMessages) {
var results = [];
for (var i = 0; i < foundMessages.length; i++) {
var rp = {};
rp.title = foundMessages[i].get("title");
rp.description = foundMessages[i].get("description");
var author = foundMessages[i].get("author");
rp.authorId = author.id;
results.push(rp);
}
promise.resolve(results);
});
当作者存在时,一切正常,但是如果不存在,则服务器崩溃。
我尝试添加此内容:
if (author.hasOwnProperty('id')) {
rp.authorId = author.id;
}
但是问题仍然没有解决。
有什么办法可以解决此问题?
最有可能是因为您正在访问undefined
对象的属性,在本例中为行中的author
,>
rp.authorId = author.id
[像Davi建议的那样,包括检查author
是否存在。
var repliesQuery = new Parse.Query("Reply"); repliesQuery.include("author"); repliesQuery.find({ useMasterKey: true }).then(function(foundMessages) { var results = []; for (var i = 0; i < foundMessages.length; i++) { var rp = {}; rp.title = foundMessages[i].get("title"); rp.description = foundMessages[i].get("description"); var author = foundMessages[i].get("author"); if (author) { rp.authorId = author.id; } results.push(rp); } promise.resolve(results); });
您的支票
if (author.hasOwnProperty('id')) { rp.authorId = author.id; }
还访问
author
的属性,因此如果author
为undefined
,它将再次引发错误。