MongoDB Mongoose架构设计

时间:2015-04-21 01:11:48

标签: node.js mongodb mongoose

我有一个架构设计问题。我有一个UserSchema和一个PostSchema。

var User = new Schema({
  name: String
});

var Post = new Schema({
 user: { type: Schema.Types.ObjectId } 
});

此外,用户可以关注其他用户。帖子可以被其他用户喜欢。 我想查询用户的关注者和用户的关注,使用mongoose功能,例如限制,跳过,排序等。我还想查询用户喜欢的帖子。

基本上,我唯一的解决方法就是在每个模式中保留双引用。模式变为

var User = new Schema({
  name: String,
  followers: [{ type: Schema.Types.ObjectId, ref: "User" }],
  following: [{ type: Schema.Types.ObjectId, ref: "User" }]
});

var Post = new Schema({
 creator: { type: Schema.Types.ObjectId, ref: "User" },
 userLikes: [{ type: Schema.Types.ObjectId, ref: "User" }]
});

所以,将用于查询的代码

// Find posts that I create
Post.find({creator: myId}, function(err, post) { ... });

// Find posts that I like
Post.find({userLikes: myId}, function(err, post) { ... });

// Find users that I follow
User.find({followers: myId}, function(err, user) { ... });

// Find users that follow me
User.find({following: myId}, function(err, user) { ... });

除了像这样看似容易出错的双重引用之外还有其他方法吗?

1 个答案:

答案 0 :(得分:4)

实际上,您不需要双重参考。我们假设您保留following引用。

var User = new Schema({
  name: String,
  following: [{ type: Schema.Types.ObjectId, ref: "User" }]
});

您可以使用.populate()来吸引您关注的用户:

编辑:添加了跳过/限制选项以显示分页示例

User.findById(myId).populate({ path:'following', options: { skip: 20, limit: 10 } }).exec(function(err, user) {
  if (err) {
    // handle err
  }
  if (user) {
     // user.following[] <-- contains a populated array of users you're following
  }
});

而且,正如你已经提到的那样......

User.find({following: myId}).exec(function(err, users) { ... });

...检索关注您的用户。

相关问题