在我的应用程序中,我存储评论。以前我的模型是这样的:
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}
}
每条评论 - 除了存储其详细信息 - 还包含有关作者的详细信息,例如username
, facebook_username
, device_id
从中添加了评论并且display_name
。还有一个布尔标志friends_only
基于此,我决定该评论是否应该仅对用户的 Facebook 好友或所有人可见。
建设node.js
/mongoose
获取所有评论的查询如下所示:
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 = [];
// and condition on start date
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}});
}
// and condition on hastags
if (hashtagsInput != undefined) {
var hashtags = hashtagsInput.split(",");
query.$and.push({"hashtags":{$in: hashtags}});
}
// creating a OR condition for facebook friends and public flag
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});
}
//Merging facebook friend condition with other condition with AND operator.
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}
}
and
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: {
}});
我不知道该怎么做。你能帮我吗?