I'm building a restful api using node express mongoose/mongo etc.. I'm trying to output an array of users that are being followed by a particular user. Here is the schema.
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});
So every User has array of users in an array in the key 'following'. I'm trying to output that list by first finding the user record through it's own id and then mapping through this array to find the followed users for this current user.
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);
});
Now the console.log in this code outputs the correct data in the js console but I can't seem to find a way to deliver this to the client. So far my efforts bring forth 'null' values in the client. The correct amount of records but just null values. Any ideas how to fix this?
via zookeemedia
No comments:
Post a Comment