javascript - 为什么使用子字符串方法时应用程序挂起?

标签 javascript node.js mongodb

我有一个从数据库中提取数据的应用程序:

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/

相关文章:

MongoDB elemmatch数组中的多个元素

javascript - 为什么不在数组中添加元素?

javascript - 如何检查父元素的 css 样式?

node.js - Node :- 92% chunk asset optimization TerserPlugin FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

node.js - 为什么我在尝试安装 gulp 时不断收到错误消息?

c# - 如何在反序列化的 MongoDB 文档中获取对父对象的引用?

javascript - 将非 commonJS 库包含到 Webpack 上下文中的好方法是什么?

javascript - 返回 json 时使用模板文字? Node.js

javascript - 在 Node 中,如何使用 Promise 从多个 URL 请求 JSON?

node.js - Nodejs session 维护