MongoError:在对嵌套文档中的记录进行分组时,无法从缺少的 BSON 类型转换为日期
Posted
技术标签:
【中文标题】MongoError:在对嵌套文档中的记录进行分组时,无法从缺少的 BSON 类型转换为日期【英文标题】:MongoError: can't convert from BSON type missing to Date while Grouping records in nested documents 【发布时间】:2017-10-24 16:10:10 【问题描述】:基本上我想按月份对投票进行分组。
我的模特:
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"
]
]
]
但是当我尝试使用类似于https://***.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));
);
但是我遇到了同样的错误
【问题讨论】:
【参考方案1】:经过长时间的搜索找到了解决方案:
必须首先
$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 的文档:
【讨论】:
以上是关于MongoError:在对嵌套文档中的记录进行分组时,无法从缺少的 BSON 类型转换为日期的主要内容,如果未能解决你的问题,请参考以下文章
mapReduce/Aggregation:按嵌套文档中的值分组