微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Mongoose查询嵌套文档大于或等于某一特定日期

我如何查询大于或小于某个日期的评论

这是我的模式与邮政模型和评论模型:

var mongoose = require('mongoose');
var should = require('should');

mongoose.connect("localhost","test_db");

var CommentSchema = new mongoose.Schema({
  content:    {type:String},created_at: {type:Date,default:Date.Now}

});

var PostSchema = new mongoose.Schema({
  title:    {type:String},content:  {type:String},comments: [CommentSchema]

    });

var Post = mongoose.model('Post',PostSchema);
var Comment = mongoose.model('Comment',CommentSchema);

var post = new Post({title:"hello world",comments:[{content:"1st comment"},{content:"2nd comment"}]});
// I saved it! and then I query for it

  var id = "5045d5be48af9f040f000002";
  Post.find({ _id:id,"comments.created_at":{ $gte:(new Date())}
                },function(err,result){
    console.log(result);
  });

我需要帮助查询嵌入式文档…

好的,我编辑我的代码给更多的细节.

这将返回一个空数组.所以我想要什么或我期望的是一个空的注释数组的帖子.但是有了这个查询,我根本不会收到一个帖子. (当我与$lte交换$gte时,我得到(显然)该帖子的2个评论).

但是,再次如何根据上面的描述过滤细节?

解决方法

使用 dot notation到达嵌入式阵列文档内.例如,要查询使用date1和date2之间的created_at发布评论
Post.find({ "comments.created_at": { $gt: date1,$lt: date2 }},function (err,docs) {
     ...
});

UPDATE

感谢编辑;现在我明白你试图通过create_at日期来过滤单个帖子的评论.您无法直接使用MongoDB查询,但如果您使用该版本,我相信您可以使用2.2聚合框架.看看这个feature request在Jira上的讨论例子.

原文地址:https://www.jb51.cc/js/154344.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐