我有一个从数据库中提取数据的应用程序:
db.books.find().sort({ _id: 1 }).limit(count).toArray(function (err, results) {
if (err) {
next(err, null);
} else {
next(null, results);
}
});
每本书都有一个长文本的描述,但我不想获取每本书的完整文本,所以我决定使用 map
方法来投影结果,这样我就可以得到描述的字符数:
db.books.find().sort({ _id: 1 }).limit(count)
.map(function(item) {
return {
description: item.description.substring(0, 50),
,....
}
}).toArray(function (err, results) {
if (err) {
next(err, null);
} else {
next(null, results);
}
});
但是当我使用 substring
方法时,应用程序挂起,我看不到结果。
有什么想法吗?
最佳答案
我的错!有些书没有描述,它们是未定义
。我只是通过简单的检查解决了这个问题:
description: item.description != undefined ? item.description.substring(0, 50) : 'no description',
关于javascript - 为什么使用子字符串方法时应用程序挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36954886/