【问题标题】:Mongodb,express find data by _id with multiple conditionMongodb,通过_id多条件表达查找数据
【发布时间】:2013-12-18 23:53:10
【问题描述】:

我的代码如下所示:

PostCategory.find({categoryid:category._id.str},function(err,postcategories){
            if(err) return next(err);

            Post.find({_id:postcategories.postid},function(err,posts){
            if(err) return next(err);
                return res.render(__dirname + "/views/categorydetail",  {
                    title: 'İletişim',
                    stylesheet: 'contact'
                });
            }); 
        });

我想在 postcategories.postid 中查找 _id 的所有帖子。我的 postcategories 返回我的列表。这是我的后分类模型:

module.exports = function(){
    var PostCategorySchema = new mongoose.Schema({
        postid:String,
        categoryid:String,
        createddate:{ type: Date, default: Date.now }
    });

    mongoose.model("PostCategory",PostCategorySchema);
};

有什么想法吗?

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    首先,您的 Mongoose 模型需要是这样的:

    var PostCategorySchema = new mongoose.Schema({
      postid: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
      categoryid: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
      createddate:{ type: Date, default: Date.now }
    });
    
    mongoose.model("PostCategory", PostCategorySchema);
    

    ref 选项告诉 Mongoose 在填充过程中使用哪个模型,在我们的例子中是 Post 模型(categoryid 字段也是如此)。

    之后,你的请求就变得很简单了:

    var query = PostCategory.find({ categoryid: category._id });
    query.populate('postid');
    query.exec(function (err, postcategories) {
      if (err) return next(err);
      // res.render('......');
    });
    

    有关更多信息,您应该阅读Mongoose Query Population 文档。

    编辑:

    因此,如果postcategory 有多个post,请将模型更新为:

    var PostCategorySchema = new mongoose.Schema({
      postid: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }],
      categoryid: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
      createddate:{ type: Date, default: Date.now }
    });
    

    【讨论】:

    • 好方法。谢谢。但我有不止一个帖子。 postcategories 返回我的列表。我必须找到所有帖子才能发送给他们查看。
    • 我编辑了我的答案。 postid 现在被 [] 包围。如果满意,别忘了采纳答案。
    【解决方案2】:

    简单的方法是:

    PostCategory.find({categoryid:category._id.str},function(err,postcategories){
        if(err) return next(err);
    
        var ids = [];
        _.each(postcategories, function(postCategory){
            ids.push(postCategory.postid);
        });
    
        Post.find({_id : { $in : ids } },function(err,posts){
            if(err) return next(err);
    
            return res.render(__dirname + "/views/categorydetail",  {
                title: 'İletişim',
                stylesheet: 'contact'
            });
        });
    )};
    

    在我的示例中,我使用 underscoreJS 来获取 postCategories 列表

    【讨论】:

    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    相关资源
    最近更新 更多