MongoError:无法将BSONtypes转换为date,而将嵌套文档中的logging分组

基本上我想按月分组投票。

我的模特:

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var voteSchema = new Schema({ ip: String, votedOn: { type: Date, default: Date.now } }); var choiceSchema = new Schema({ text: String, votes: [voteSchema] }); var PollSchema = new Schema({ question: { type: String, required: true }, choices: [choiceSchema] }); module.exports = mongoose.model('Polls', PollSchema); 

样本数据 :

 [ { "_id": "5914056440bfac03711966ad", "choices": [ { "text": "c3", "_id": "5914056440bfac03711966af", "votes": [ { "ip": "::1", "_id": "5914058040bfac03711966b4", "votedOn": "2017-05-11T06:32:32.685Z" } ] }, { "text": "c1", "_id": "5914056440bfac03711966ae", "votes": [ { "ip": "::1", "_id": "587dec8eaccc4b036a193a8f", "votedOn": "2017-01-17T10:06:06.012Z" } ] } ] }, { "_id": "5914057540bfac03711966b0", "choices": [ { "text": "b3", "_id": "5914057540bfac03711966b3", "votes": [ { "ip": "::1", "_id": "591d6b8caccc4b036a193a8e", "votedOn": "2017-05-18T09:38:20.363Z" } ] }, { "text": "b2", "_id": "5914057540bfac03711966b2", "votes": [ { "ip": "::1", "_id": "591d69b7accc4b036a193a8d", "votedOn": "2017-05-18T09:30:31.708Z" }, { "ip": "::1", "_id": "587dec9aaccc4b036a193a90", "votedOn": "2017-01-17T10:06:18.137Z" } ] }, { "text": "b1", "_id": "5914057540bfac03711966b1", "votes": [ { "ip": "::1", "_id": "587decafaccc4b036a193a91", "votedOn": "2017-01-17T10:06:39.809Z" } ] } ] } ] 

但是,当我尝试创build组使用mongoose的东西类似于https://stackoverflow.com/a/38596913/5871771

我得到MongoError: can't convert from BSON type missing to Date错误

我也尝试使用下面的代码获得基本的分组

 Poll.aggregate({ $group : { _id : { month: { $month: "$votes.votedOn" }, day: { $dayOfMonth: "$votes.votedOn" }, year: { $year: "$votes.votedOn" } } } }, function(err, d) { if (err) { throw err; } console.log(JSON.stringify(d, null, 4)); } ); 

但我得到同样的错误

长时间搜寻后find解决scheme:

你必须首先$unwind数组,以便mongodb可以访问数组对象

以下代码工作正常

 Poll.aggregate( // Un-wind the array's to access filtering { $unwind: "$choices" }, { $unwind: "$choices.votes" }, { $unwind: "$choices.votes.votedOn" }, // Group results to obtain the matched count per key { $group: { _id : { month: { $month: "$choices.votes.votedOn" }, year: { $year: "$choices.votes.votedOn" } }, count: { "$sum": 1 } }}, function(er, d) { console.log(d) } ) 

这将导致我需要的东西

 [ { _id: { month: 1, year: 2017 }, count: 3 }, { _id: { month: 5, year: 2017 }, count: 3 } ] 

请参阅文档$ unwind :