es6mongoose嵌套findById诺言

我正在build立一个使用节点快速mongoose / mongo等宁静api。我试图输出一个特定的用户正在跟踪的用户数组。 这是架构。

var UserSchema = new mongoose.Schema({ username: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true}, email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true}, bio: String, image: String, following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] }, {timestamps: true}); 

所以每个用户都有一个数组中的用户在“关注”后面的数组中。 我试图输出该列表,首先通过它自己的idfind用户logging,然后映射通过这个数组来find当前用户的后续用户。

 router.get('/users/friends', auth.required, function(req, res, next) { var limit = 20; var offset = 0; if(typeof req.query.limit !== 'undefined'){ limit = req.query.limit; } if(typeof req.query.offset !== 'undefined'){ offset = req.query.offset; } User.findById(req.payload.id) .then(function(user){ if (!user) { return res.sendStatus(401); } return res.json({ users: user.following.map(function(username){ User.findById(username) .then(function(userlist){ console.log('userlist:',userlist.username); return userlist.username; }) .catch(next) }) }) }) .catch(next); }); 

现在这个代码中的console.log在js控制台中输出正确的数据,但我似乎无法find一种方法将其传递给客户端。 到目前为止,我的努力给客户带来了“零”价值。 正确的logging数量,但只是空值。 任何想法如何解决这一问题?

修改我的代码后,采取下面的build议。 现在它设法得到客户的第一个logging,但随后出错

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):错误:发送后无法设置标头。 大段引用

 router.get('/users/friends', auth.required, function(req, res, next) { var limit = 20; var offset = 0; if (typeof req.query.limit !== 'undefined') { limit = req.query.limit; } if (typeof req.query.offset !== 'undefined') { offset = req.query.offset; } User.findById(req.payload.id) .then(function(user) { if (!user) { return res.sendStatus(401); } Promise.all( user.following ).then(function(userarray) { console.log(userarray); userarray.forEach(function(userid) { Promise.all([ User.find({ _id: { $in: userid } }) .limit(Number(limit)) .skip(Number(offset)) .populate('author') .exec() ]).then(function(results) { userdetails = results[0]; var userdetailsCount = results[1]; return res.json({ userdetails: userdetails.map(function(userdetail){ return userdetail; }) }); }) }) }) }) .catch(next); }); 

您的问题部分是:

 return res.json({ users: user.following.map(function(username){ User.findById(username) .then(function(userlist){ console.log('userlist:',userlist.username); return userlist.username; }) .catch(next) }) }) 

User.findById(username)位将返回一个承诺。 但是你不是在等待这个承诺。 我猜你认为那个遵循这个承诺的函数,将userlist.usernamelogging到控制台并返回它,应该意味着你的map函数返回一个userlist.username的列表。 但这种情况并非如此。 你的map函数正在返回一个promise数组。

你真正想要的是像Bluebird的Promise.map这样的Promise.map : http : Promise.map (或者寻找一个类似的function来处理promise中的数组,你碰巧正在使用)。