返回单个响应中的mongoose错误列表

我目前正在使用Node.js,Mongoose和Express.js后端开发。 这是我尝试使用mongoose创build的用户列表。

[ { "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()内的值谢谢。

使用内置的承诺支持,而不是callback,这与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 });