node.js - Easy way to reference Documents in Mongoose -


in application have user collection. many of other collections have author (an author contains user._id , user.name), example post collection. since need _id , name display e.g. posts on ui.

this works fine, , seems approach, since everytime deal posts don`t have load whole user object database - can load post.author.userid/post.author.name.

now problem: user changes or name. author objects scattered around in database still have old author.

questions:

  1. is approuch solid, or should reference userid everywhere need it?

if i'd go solution i'd remove author model , need make user database call everytime want display current users`s name.

  1. if leave author is, way implement solution situations user.name change?

i write service checks every model has authors of current user._id , updates them of course, sounds tedious. although i'm not sure there's better solution.

  1. any pro tipps on how should deal problems in future?

yes, sometime database recorded @ modular style. shouldn't separating collection user/author such @ time if use mongoose driver can use populate user schema data.

example, 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 style, post separated model , have save that. if want query post including author's name, can use populate @ mongoose.

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

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -