mercredi 14 juillet 2021

Unable to apply cursor methods to array of projected IDs in a variable using async/await in Mongoose

I have the following code which works just fine:

            try {
                const retrievedCursor = await JobListing.find(object, { projection: { _id: 1 } }).sort({ _id: -1 }).skip(skipSize).limit(1)
                -- More lines of code until I get the actual results...--
                res.status(200).json({ message: 'Published jobs: ', results})
            } catch (error) {
                res.status(400).json({ message: 'Failed GET'})
            }

However, I want to get the length of JobListing.find(object, { projection: { _id: 1 } }) (which is an array) in a variable and then apply the sort(), skip() & limit() methods to that variable. Hence, I am doing:

            try {
                const initialResult = await JobListing.find(object, { projection: { _id: 1 } })
                const secondaryResult = await initialResult.sort({ _id: -1 }).skip(skipSize).limit(1)
                -- More lines of code until I get the actual results...--
                res.status(200).json({ message: 'Published jobs: ', results})
            } catch (error) {
                res.status(400).json({ message: 'Failed GET'})
            }

As a result, initialResult is an array of documents, and secondaryResult simply doesn't come up with anything. What am I doing wrong? The entire code is within an asynchronous function, needless to say.

My interest is getting the length of the array with projected IDs to display the total number of found documents on my front end.

Aucun commentaire:

Enregistrer un commentaire