[英]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
: 我需要基于电子邮件数组查询数据库中的用户,然后为每个结果执行一个函数,我使用
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. 我遇到的问题是,如果有给定电子邮件的任何用户不存在,我需要返回
404
状态。
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. 用
.then
简单地“解析” DocumentQuery
是行不通的,因为之后便无法将其转换为光标。
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!' });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.