简体   繁体   中英

Perform side effects for mongoose/mongodb query

I need to query my database for users based on an array of emails and then execute a function for each result, I do this with eachAsync :

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

    // do stuff
  });

The problem I'm having is that I need to return a 404 status if any of the users with the given emails do not exist.

I've been looking through the mongoose docs but I can't seem to find a way of running "side effects" when working with queries. Simply "resolving" the DocumentQuery with .then doesn't work since you can't turn it into a cursor afterwards.

How can I achieve this?

You could try implementing it as shown below. I hope it helps.

// 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!' });
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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