将数据从一个模型拆分为两个后,如何重写我的mongoose查询?

时间:2016-12-18 20:33:49

标签: node.js mongodb mongoose mongoose-populate

在我的应用程序中,我存储了评论。以前我的模型看起来像这样:

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}
}

每条评论 - 除了存储其详细信息外 - 还有关于作者的详细信息,例如:已添加评论的usernamefacebook_usernamedevice_iddisplay_name。还有一个bool标志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}
}

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: {

}});

我不知道该怎么做。你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用填充查询,如果您认为填充不会为您提供所需的数据,您可以运行两个查询并合并这些结果。

对于populate,我从mongoose的官方文档中找到了解决方案。你可以这样做

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
  if (err) return handleError(err);
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
});

这里是文档链接:http://mongoosejs.com/docs/populate.html