如何检查用户是否已经关注NodeJs中的其他用户 - Mongoose

时间:2015-03-19 10:39:59

标签: javascript node.js mongodb mongoose mongodb-query

我有一个followSchema:

var followSchema = mongoose.Schema({ 
    user : { type: Number, ref: 'User'},
    following : { type: Number, ref: 'User'}
});

我有两个用户。 在第一个中,我需要列出他所遵循的所有用户。 第二个我需要检查他是否已经跟踪了我从第一个用户收集的一些用户。

我怎样才能在猫鼬中以情感的方式做到这一点。 从第一个用户那里获取关注者列表并不难,但要检查第二个用户是否遵循其中一个更难,我不知道如何管理它。

2 个答案:

答案 0 :(得分:2)

这很简单,您需要做的就是查询这两个条件。假设“跟随”作为模型:

Follow.find({
   "user": 1,
   "following": 2
})

根据您的“比例”,以下架构可能更有用:

var userSchema = new Schema({
    "_id": Number,
    "name": String,
    "following": [{ "type": Number, "ref": "User" }],
    "followedBy": [{ "type": Number, "ref": "User" }]
})

查询几乎相同:

User.find({
    "_id": 1,
    "following": 2
})

但是,当然它总是为您提供其他选择,只要遵守“数组”最佳实践的一般约束即可。

答案 1 :(得分:1)

您可以采取的一种方法是修改followSchema,将following字段作为数组,并使用 population 的概念:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var userSchema = Schema({
    _id: Number,
    name: String,
    age: Number,
    followers: [{ type: Schema.Types.ObjectId, ref: 'Follow' }]
});

var followSchema = Schema({
    _user: { type: Number, ref: 'User' },
    following: [{ type: Number, ref: 'User' }]
});

var Follow  = mongoose.model('Follow', followSchema);
var User = mongoose.model('User', userSchema);

然后您可以使用一些示例用户进行查询。作为示例指南(未经测试):

var user1_id = 1,
    user2_id = 2,    
    user3_id = 3,   
    user1_following = [], 
    user2_following = [];

var user1 = new User({ _id: user1_id, name: 'User1', age: 31 });
var user2 = new User({ _id: user2_id, name: 'User2', age: 32 });
var user3 = new User({ _id: user3_id, name: 'User3', age: 32 });

user3.save(function (err) {
     if (err) return handleError(err);       
})

user1.save(function (err) {
     if (err) return handleError(err);  
     var follower3 = new Follow({ _user: user3_id });           
     follower3.save(function (err) {
        if (err) return handleError(err);
        // thats it!
     });
})

user2.save(function (err) {
     if (err) return handleError(err);  
     var follower3 = new Follow({ _user: user3_id });         
     follower3.save(function (err) {
        if (err) return handleError(err);
        // thats it!
     });
})

Follow
    .find({ _user: user1_id })
    .exec(function (err, following) {
         if (err) return handleError(err);
         user1_following = following;
   })    

Follow
    .find({ _user: user2_id })
    .exec(function (err, following) {
         if (err) return handleError(err);
         user2_following = following;
   }) 

然后,您可以使用下划线的 intersection() ,它会为您提供两个阵列中存在的值列表。

var commonFollowings = _.intersection(user1_following, user2_following);
// In the example above, commonFollowings => [3]