MongoDB Mongoose Schema Design

I have a question of designing a circuit. I have UserSchema and PostSchema.

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

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

In addition, the user can monitor other users. Other users may like the message. I would like to request the followers of the User and the User using mongoose functions such as restriction, skip, sort, etc. I also want to request a message that the user likes.

Basically, my only attempt to solve this is to keep a double link in each schema. Schemes become

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" }]
});

therefore the code to be used for the request

// 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) { ... });

Is there a way other than double link like this that seems error prone?

+4
source share
1

, . , following.

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

.populate(), , :

EDIT: /,

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) { ... });

... , .

+4

All Articles