如何循环的数据和验证在MongoDB中
我有一个动态输入字段,用户可以一次添加多个类别。在后台发送的数据是一样
['ELECTRONIC','TOYS','GAMES']
现在,我想检查数组的每一个元素,如果它们已存在于MongoDB的。如果其目前我想将其存储在errors
对象
errors={ 0: 'Duplicate Data found'}
我附上我的代码,用于没有工作,请帮忙验证。 。
const Category = require('../../models/Category');
const fieldCheck = (req, res, next) => {
const data = req.body;
const errors = [];
for( i = 0; i < data.length ; i++){
Category.findOne({ category_name : data[i]})
.then(user => {
if(user){
// # If a reqistered User ID is found ,then move ahead
errors[i] = 'Duplicate Entry Found';
errors.push(errors[i]);
}
}).catch(err =>{
return res.json(err);
}
)
}
console.log(errors);
};
module.exports = fieldCheck;
回答如下:
您正在尝试调用一个同步环(findOne
)内的异步方法(for
)。当你的经验,这就像油和水。
一个简单的办法就是让你的方法异步和使用await
关键字,例如:
const fieldCheck = async (req, res, next) => {
const data = req.body;
const errors = [];
try {
for( i = 0; i < data.length ; i++) {
let user = await Category.findOne({ category_name : data[i]});
if (user) {
// # If a reqistered User ID is found ,then move ahead
errors[i] = 'Duplicate Entry Found';
errors.push(errors[i]);
}
}
// I assume you wanted to respond to res.json here?
console.log(errors);
} catch (err) {
return res.json(err);
}
};
module.exports = fieldCheck;
与本文相关的文章
评论列表(0)
- 暂无评论