Markus
Markus

Reputation: 1563

Easy way to reference Documents in Mongoose

In my application I have a User Collection. Many of my other collections have an Author (an author contains ONLY the user._id and the user.name), for example my Post Collection. Since I normally only need the _id and the name to display e.g. my posts on the UI.

This works fine, and seems like a good approach, since now everytime I deal with posts I don`t have to load the whole user Object from the database - I can only load my post.author.userId/post.author.name.

Now my problem: A user changes his or her name. Obviously all my Author Objects scattered around in my database still have the old author.

Questions:

  1. is my approuch solid, or should I only reference the userId everywhere I need it?

If I'd go for this solution I'd remove my Author Model and would need to make a User database call everytime I want to display the current Users`s name.

  1. If I leave my Author as is, what would be a good way to implement a solution for situations like the user.name change?

I could write a service which checks every model which has Authors of the current user._id and updates them of course, but this sounds very tedious. Although I'm not sure there's a better solution.

  1. Any pro tipps on how I should deal with problems like this in the future?

Upvotes: 0

Views: 768

Answers (2)

greenlikeorange
greenlikeorange

Reputation: 505

Yes, sometime database are good to recorded at modular style. But You shouldn't do separating collection for user/author such as At that time if you use mongoose as driver you can use populate to get user schema data.

Example, I modeling user, author, post that.

var UserSchema = new mongoose.Schema({ 
  type: { type: String, default: "user", enum: ["user", "author"], required: true },
  name: { type: String },

  // Author specific values
  joinedAt: { type: Date }
});
var User = mongoose.model("User", UserSchema);

var PostSchema = new mongoose.Schema({ 
  author: { type: mongoose.Scheam.Types.ObjectId, ref: "User" },
  content: { type: String } 
});
var Post = mongoose.model("Post", PostSchema);

In this style, Post are separated model and have to save like that. Something like if you want to query a post including author's name, you can use populate at mongoose.

Post.findOne().populate("author").exce(function(err, post) {
  if(err)
    // do error handling
  if(post){
    console.log(post.author.type) // author 
  }
});

Upvotes: 1

Edgar
Edgar

Reputation: 1313

One solution is save only id in Author collection, using Ref on the User collection, and populate each time to get user's name from the User collection.

var User = {
    name: String,
    //other fields
}

var Author = {
    userId: {
        type: String,
        ref: "User"
    }
}

Another solution is when updating name in User collection, update all names in Author collection.

I think first solution will be better.

Upvotes: 1

Related Questions