My application stores comments. Previously, my model for this looked like this:
var CommentsSchema = new Schema({
username: {type: String},
display_name: {type: String},
facebook_username: {type: String},
text_content: {type: String},
photo_content_url: {type: String},
hashtags: {type: [String]},
device_id: {type: String},
comment_date: {type: Date, default: Date.now},
friends_only: {type: Boolean, default: false}
}
In each comment, in addition to preserving its details, there were also detailed information about the author, for example. username, facebook_username, device_idFrom which the comment was added, and display_name. There was also a bool flag friends_only, based on which I decided whether this comment should be visible only to users of facebook friends or for everyone.
Building a request node.js/ mongooseto get all comments is as follows:
commentsRoutes.post('/friends', function (req, res) {
var friends = req.body.friends;
var publicComments = req.body.publicComments;
var hashtagsInput = req.body.hashtags;
var startDate = req.body.startDate;
var endDate = req.body.endDate;
var query= {};
query.$and = [];
if(startDate != undefined) {
var startDate = new Date(req.param('startDate'));
var endDate = new Date(req.param('endDate'));
query.$and.push({"comment_date":{$gte: startDate}});
query.$and.push({"comment_date":{$lte: endDate}});
}
if (hashtagsInput != undefined) {
var hashtags = hashtagsInput.split(",");
query.$and.push({"hashtags":{$in: hashtags}});
}
var friend_query = {};
friend_query.$or = [];
if (friends != undefined) {
var friendsSplit = friends.split(",");
friend_query.$or.push({"facebook_username":{$in: friendsSplit}});
}
if (publicComments != undefined && publicComments === "true") {
friend_query.$or.push({friends_only: false});
}
query.$and.push(friend_query);
var finalQuery = Comment.find(query)
, ( , ) ( ).
. :
var CommentsSchema = new Schema({
user_id: {type: String, required: true, ref: 'users' },
text_content: {type: String},
photo_content_url: {type: String},
hashtags: {type: [String]},
comment_date: {type: Date, default: Date.now},
friends_only: {type: Boolean, default: false},
device_id: {type: String}
}
var UsersSchema = new Schema({
username: {type: String},
facebook_username: {type: String},
display_name: {type: String}
}
, , , .
async, mongoose .populate. , , or match populate:
...
var finalQuery = Comment.find(query)
finalQuery.populate({path: 'user_id',
select: 'facebook_username display_name username',
match: {
}});
, . ?