ftdeveloper
ftdeveloper

Reputation: 1093

Mongodb,express find data by _id with multiple condition

My code is shown below:

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

I want to find all post which _id is in postcategories.postid. My postcategories returns me list. Here is my postcategories model:

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

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

Any idea?

Upvotes: 0

Views: 1234

Answers (2)

Sandro Munda
Sandro Munda

Reputation: 41030

First of all, your Mongoose model needs to be something like that:

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

The ref option is what tells Mongoose which model to use during population, in our case the Post model (same thing for categoryid field).

After that, your request becomes really simple:

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

For more information, you should read the Mongoose Query Population documentation.

EDIT:

So, if you have more than one post for a postcategory, update the model to:

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

Upvotes: 1

throrin19
throrin19

Reputation: 18197

the simple way is :

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

In my example, i use underscoreJS to fetch postCategories List

Upvotes: 0

Related Questions