我正在使用node express mongoose/mongo等构建一个restful 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});
因此,每个用户在键“following”的数组中都有用户数组。我试图输出该列表,首先通过用户自己的 id 查找用户记录,然后通过该数组进行映射以查找当前用户的关注用户。
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控制台中输出了正确的数据,但我似乎找不到将其传递给客户端的方法。到目前为止,我的努力在客户端中带来了“空”值。正确的记录数量,但只是空值。有什么想法可以解决这个问题吗?
在听取下面的建议后,我将我的代码修改为这样。现在它成功地将第一条记录发送给客户端,但随后出现错误
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. Blockquote
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)
位将返回一个 promise 。但你并没有等待这个 promise 。我猜您认为遵循该 promise 的 then
函数将 userlist.username
记录到控制台并返回它,应该意味着您的 map
函数返回 userlist.username
的列表。但这种情况并非如此。您的 map
函数返回一个 Promise 数组。
您真正想要的是像 Bluebird 的 Promise.map
这样的功能:http://bluebirdjs.com/docs/api/promise.map.html (或者,在您碰巧使用的任何 Promise 库中寻找类似的功能来处理 Promise 数组)。
关于arrays - es6 Mongoose 嵌套findById promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969555/