Mongodb,通过具有多个条件的_id快速查找数据

Mongodb,express find data by _id with multiple condition

本文关键字:id 数据 查找 条件 Mongodb      更新时间:2023-09-26

我的代码如下所示:

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'
                });
            }); 
        });

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

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

知道吗?

首先,你的猫鼬模型需要是这样的:

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 选项告诉猫鼬在种群期间使用哪个模型,在我们的例子中是 Post 模型(categoryid字段也是如此)。

之后,您的请求变得非常简单:

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

有关更多信息,您应该阅读猫鼬查询种群文档。

编辑:

因此,如果一个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 }
});

简单的方法是:

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'
        });
    });
)};

在我的示例中,我使用下划线JS来获取postCategories列表