在mongoose

时间:2017-04-10 15:04:56

标签: mongodb mongoose populate mongoose-populate

我正在查询用户的用户连接。我还想显示该用户的用户连接的最新标语。

由于标语在用户模型中而不在用户连接中,我需要在获取用户连接的同时获取它。

现在我用$ in做,是填充更好的选择吗?有一个更好的方法吗?由于标语可能会被用户更新,我不希望将它们存储在用户连接中,否则如果标语更改,我必须始终更新每个用户连接。

我的用户连接模型:

var UserConnectionsSchema   = new Schema({

    userID: {type: String, index: true},
    userName: String,  
    userTargetID: String,
    userTargetName: String,
    connectionStatus: String,
});

我的用户模型的摘录

var UserSchema   = new Schema({

    name: String,
    email: { type: String, required: true, index: { unique: true }},
    password: { type: String, select: false },

    tagline: String,

});

以下是我目前使用$ in获取标语的方式:

apiRouter.route('/users')

        .get(function(req, res) {

            UserConnection.find( { $and : [ { userID : req.decoded.id }, 
                { connectionStatus : 'accepted' } ] }).sort({'_id': -1}).limit(30).exec(function(err, connections) {
                if (err) res.send(err); 

                //we also find the taglines for the users
                if (!err) {
                    searchArray = [];
                    for (i=0; i < connections.length; i++) {
                        searchArray.push(connections[i].userTargetID);
                    }
                    console.log(searchArray);

                    User.find({'_id': { $in: searchArray }}).select("tagline").exec(function(err2, users){                      
                        if (err2) res.send(err2);
                        console.log(users);
                        if (!err2) {    
                            res.json({"connections": connections, "users": users});
                        }
                    });

                }

            });
        });

0 个答案:

没有答案