我有这个 Mongoose 模式
var SessionSchema = mongoose.Schema({
id: Number,
cure: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Cure'
},
performances: Array,
startDate: Date,
endDate: Date,
validatee: Boolean,
deleted: Boolean
});
我需要知道有多少文档有不同的 ID,但我只需要那些 startDate
大于给定日期(例如今天)的文档。
运行以下代码工作正常,但我想在 map 中添加一些字段以在查询中使用它们。
var o = {};
o.map = function () {
emit(this.id, 1
// list other fields like above to select them
)
}
o.reduce = function (k, vals) {
return vals.length
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime)
console.log("MapReduce" + JSON.stringify(model));
model.find().exec(function (err, docs) {
console.log(docs);
});
});
这是我的输出:
[ { _id: 0, value: 2 },
{ _id: 1, value: 4 },
{ _id: 2, value: 2 } ]
我尝试这样做:
....
o.map = function () {
emit(this.id, {
startDate: this.startDate
})
}
....
model.find({
startDate: {
"$gte": new Date()
}
}).exec(function (err, docs) {
console.log(docs);
});
....
但我一直得到相同的输出。
那么如何将更多的键值参数从 map 函数添加到 reduce 函数的结果字典中呢?
最佳答案
这是一个解决方案:
var o = {};
o.map = function () {
emit(this.id, {
startDate: this.startDate,
cure: this.cure,
test: 'test'
// list other fields like above to select them
})
}
o.reduce = function (k, vals) {
return {
n: vals.length,
startDate: vals[0].startDate,
cure: vals[0].cure,
test: vals[0].test
}
}
o.out = {
replace: 'createdCollectionNameForResults'
};
o.verbose = true;
Session.mapReduce(o, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime);
model.find({
'value.cure':mongoose.Types.ObjectId('52aedc805871871a32000004'),
'value.startDate': {
"$gte": new Date()
}
}).exec(function (err, docs) {
if(!err)
console.log(docs.length);
});
});
关于javascript - 使用 Mongoose 和 NodeJS 在 MapReduce 中添加更多字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20681189/