Mongodb,通过具有多个条件的_id快速查找数据
Mongodb,express find data by _id with multiple condition
我的代码如下所示:
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列表
相关文章:
- 使用angularjs中的rest调用通过id获取数据
- tu如何将id放在填充了json数据的html表td上
- 为什么数据列表选项的id返回空值
- 使 ajax 请求和成功数据显示在 id <选择>选择>部分中
- 数据互绑定问题:转换器只运行一次,无法绑定元素的 ID
- 按 ID 存储关联数据
- asp.net 数据列表中的跟踪标签 ID
- 使用 JQuery 隐藏没有数据(包括标头)且具有相同表 ID 的列
- jquery没有't从DIV数据id中获取PHP变量值,只输出变量名
- 有没有办法用$('#id').uploadifive('upload');发送额外的数据
- 数据id是否违反关注点分离
- 对话框,数据选择器获取id
- 通过ID获取声明性dojo数据网格
- Xcode 从 WebView 解析 HTML ID 数据
- Richfaces:如何根据事件后返回的事件.rf.data来呈现id数据可用
- 无法使用平面UI选择框获取要显示的ID数据
- 如何从外部json文件中获取id数据,并在url中显示id号,当使用jQuery单击项目时
- 导航到具有与click元素的data-id数据属性相同的id的元素
- 我如何获得一个特定的Id数据从本地存储使用jquery编辑表单
- 如何通过单击JQuery按钮来提取id数据