Tryst with Mongoose - Part 1
I discovered something about Mongoose that I did not know until yesterday, while working on a side project.
Imagine that you have a schema called Tweets and all tweets have comments. The problem I was trying to solve was to determine whether or not the current logged in user had liked a particular comment on a Tweet. Assume the schema looks like this:
var Tweets = new Schema({
comments: [comments]
author: { type: Schema.Types.ObjectId, ref: 'User' }
}, { toObject: { virtuals: true }, toJSON: { virtuals: true } });
var Comments = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'User' }
}, { toObject: { virtuals: true }, toJSON: { virtuals: true } });
Assume that allLikedComments
is an array of the all the commentIds that the current user has liked. I am iterating through each comment in a tweet and I am figuring out whether or not it's a part of allLikedComments.
Tweets.find({_id : tweetId}).exec(
function(err, tweet) {
if (err)
//return and throw error
tweet.comments = _.map(tweet.comments,
function(comment){
comment.likedbyCurrentUser =
_.contains(allLikedComments, comment._id);
console.log(comment.likedbyCurrentUser);
return comment;
}
);
}
);
So far so good. Even the console.log statement shows me whether or not the current user has liked the current post. The only problem is when I return the tweet object to the client, the objects in the comment array do not have a likedbyCurrentUser
property. Go figure!
As things turn out, likedbyCurrentUser
should be a part of the Comments schema. Say what now! Sure, this worked. However, I don't really need to save the likedbyCurrentUser
in the database since we compute it on the fly.
That's where virtual attributes come in. Here's how one can define virtual attributes.
Virtual attributes are attributes that are convenient to have around
but that do not get persisted to mongodb.
I will write more about virtual attributes in the part 2 of this article very very soon and how one can use virtual attributes to solve the problem we discussed . Let me know your thoughts!