gpt4 book ai didi

node.js - 蒙哥错误: can't convert from BSON type missing to Date while Grouping records in nested documents

转载 作者:可可西里 更新时间:2023-11-01 10:41:00 26 4
gpt4 key购买 nike

基本上我想根据月份对民意调查进行分组。

我的模型:

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://stackoverflow.com/a/38596913/5871771 的 mongoose 创建组时

我收到 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));
}
);

但是我得到了同样的错误

最佳答案

经过长时间的搜索找到了解决方案:

One have to first $unwind the array so the mongodb can access array objects

以下代码运行良好

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 的文档:

关于node.js - 蒙哥错误: can't convert from BSON type missing to Date while Grouping records in nested documents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44156275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com