I have to create social network like twitter people post tweet but has comment in it. I defined
var Comment = new Schema();
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});
var TweetSchema = new Schema ({
created_at : { type: Date, default: Date.now }
, created_by: { type: Schema.Types.ObjectId, ref: 'User' }
, title : String
, comments : [Comment]
, body : String
, picture: [Url]
})
Because I write for mobile application request through rest api I provide I wanna ask when I create a tweet what can I send to server to have creator_info and comment to I have read something here How to populate a sub-document in mongoose after creating it? But I dont know how to write a method to create a tweet or comment and set creator for this. Thank for advance.
You can do. Before saving a tweet, you try to create a User from the data. if it fails, pass the error. If not, set the created_by field to be the user's id.
Look here for more info: http://mongoosejs.com/docs/middleware.html
TweetSchema.pre('save', function(next) {
var user = new User(this.created_by, function(err, user) {
if (err) return next(err);
this.created_by = user._id;
next();
});
});