繁体   English   中英

对mongoose / mongodb查询执行副作用

[英]Perform side effects for mongoose/mongodb query

我需要基于电子邮件数组查询数据库中的用户,然后为每个结果执行一个函数,我使用eachAsync

mongoose.model('User')
  .find({email: {$in: ['foo@bar.com', 'bar@foo.com']}})
  /* -- Run side effects before continuing -- */
  .cursor()
  .eachAsync((doc) => {

    // do stuff
  });

我遇到的问题是,如果有给定电子邮件的任何用户不存在,我需要返回404状态。

我一直在浏览猫鼬文档,但在使用查询时似乎找不到运行“副作用”的方法。 .then简单地“解析” DocumentQuery是行不通的,因为之后便无法将其转换为光标。

我该如何实现?

您可以尝试实现它,如下所示。 希望对您有所帮助。

// Function using async/await
    getCursor: async (_, res) => {
        try {
            const result = []; // To hold result of cursor
            const searchArray = ['foo@bar.com', 'bar@foo.com'];
            let hasError = false; // to track error when email from find isn't in the array

            const cursor = await mongoose.model('User').find({ email: { $in: searchArray } }).cursor();

            // NOTE: Use cursor.on('data') to read the stream of data passed
            cursor.on('data', (cursorChunk) => {
                // NOTE: Run your side effect before continuing
                if (searchArray.indexOf(cursorChunk.email) === -1) {
                    hasError = true;
                    res.status(404).json({ message: 'Resource not found!' });
                } else {
                    // Note: Push chunk to result array if you need it
                    result.push(cursorChunk);
                }
            });

            // NOTE: listen to the cursor.on('end')
            cursor.on('end', () => {
                // Do stuff or return result to client
                if (!hasError) {
                    res.status(200).json({ result, success: true });
                }
            });

        } catch (error) {
            // Do error log and/or return to client
            res.status(404).json({ error, message: 'Resource not found!' });
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM