我目前正在使用Node.js,Mongoose和Express.js进行后端开发。这是我尝试使用mongoose创建的用户列表。
[
{
"username" : "abc",
"password" : "123",
"displayname" : "ABC",
"email" : "test@example.com"
},
{
"username" : "def",
"password" : "123",
"displayname" : "DEF",
"email" : "test2@example.com"
},
{
"username" : "ghi",
"password" : "123",
"displayname" : "GHI",
"email" : "test@example.com"
}
]
这就是我目前在后端做的事情。我将用户名字段设置为unique
,如果其中一个用户名已经存在,则mongoose将返回错误。
var lists = req.body;
lists.forEach(function(list) {
var user = new User();
user.username = list.username;
user.email = list.email;
user.displayname = list.displayname;
user.password = hashed(list.password);
user.save(function(err, user) {
if (err) {
console.log(list.username + ' is already registered.');
}
});
});
res.json({
message: 'Users are successfully created'
});
我正在尝试返回已存在于数据库中的用户列表,但我只能通过console.log
执行列表而不是响应json。
abc is already registered.
gef is already registered.
有没有办法解决这个问题?我无法将值保存在user.save()
谢谢。
答案 0 :(得分:1)
使用内置的promise支持而不是回调,这对于Promise.all
来说变得微不足道了:
Promise.all(lists.map(list => { // .all waits for an array of promises.
var user = new User(); // we `.map` which transforms every element of the array
user.username = list.username;
user.email = list.email;
user.displayname = list.displayname;
user.password = hashed(list.password);
return user.save().then(x => null,e => `${list.username} already reistered`);
}).then(results => { // results of all save promises
const errors = results.filter(Boolean); // we mapped successes to null in the `then`
res.json(errors); // return all the errors
});