[英]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.