我正在使用MongoDB版本3.4.7,Mongoose 4.11.13驱动程序在MongoDB集合上创建Model并创建AggregationCursor来单独处理每个文档以填充一些JS变量。但似乎Mongoose模型没有将任何数据带入MongoDB集合的游标中。
我以前曾尝试使用mongodb
驱动程序进行聚合操作,但它不起作用
(check here)并选择了mongoose
。但似乎这里也存在一些问题,或者我在这里遗漏了什么?更新了我的AggregationCursor以便更好地理解。任何快速帮助将不胜感激。
节点版本3.10.10,ExpressJS 3.2.6
My Node.JS代码如下:
app.get('/reviews',function(req,res)
{
res.render("chart");
var obj = {};
var mongoose = require('mongoose');
var assert = require('assert');
var schema = new mongoose.Schema({
seller_id: String,
product_id: String,
product_desc: String,
reviews: {
total_review_count: Number,
five_star_count: Number,
four_star_count: Number,
three_star_count: Number,
two_star_count: Number,
one_star_count: Number
}
});
//specify the name of MongoDB collection as third argument of model
var ProductReview = mongoose.model('ProductReview', schema, 'product_reviews'); //<-- here
//review count placeholders
var totalReviewCounts = [], FiveStarCounts = [], FourStarCounts = [], ThreeStarCounts = [],
TwoStarCounts = [], OneStarCounts = [];
mongoose.connect('mongodb://localhost:27017/sellerrank', function() {
var cursor = ProductReview.aggregate([
{
$match: {
seller_id: { $exists: true, $nin: [null] }
}
}
])
.allowDiskUse(true)
.group({ _id: { seller_id: '$seller_id'},
total_review_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.total_review_count", null] },
0,
"$reviews.total_review_count"
]
}
},
five_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.five_star_count", null] },
0,
"$reviews.five_star_count"
]
}
},
four_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.four_star_count", null] },
0,
"$reviews.four_star_count"
]
}
},
three_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.three_star_count", null] },
0,
"$reviews.three_star_count"
]
}
},
two_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.two_star_count", null] },
0,
"$reviews.two_star_count"
]
}
},
one_star_count: {
$sum: {
$cond : [
{ $eq : ["$reviews.one_star_count", null] },
0,
"$reviews.one_star_count"
]
}
}
})
.cursor({ batchSize: 100})
.exec();
console.log(cursor); **//<-- printing the cursor here**
cursor.each(function(err,doc){
assert.equal(null,err);
console.log(doc);
if(doc!=null){
var seller_id = doc['_id'];
var totalReviews = doc['total_review_count'];
var fiveStarReviews = doc['five_star_count'];
var fourStarReviews = doc['four_star_count'];
var threeStarReviews = doc['three_star_count'];
var twoStarReviews = doc['two_star_count'];
var oneStarReviews = doc['one_star_count'];
totalReviewCounts.push({"value" : totalReviews});
FiveStarCounts.push({"value" : fiveStarReviews});
FourStarCounts.push({"value" : fourStarReviews});
ThreeStarCounts.push({"value" : threeStarReviews});
TwoStarCounts.push({"value" : twoStarReviews});
OneStarCounts.push({"value" : oneStarReviews});
}
});
});
var dataset = [
{
"seriesname" : "Total positive reviews",
"data" : totalReviewCounts
},
{
"seriesname" : "5 star reviews",
"data": FiveStarCounts
},
{
"seriesname" : "4 star reviews",
"data" : FourStarCounts
},
{
"seriesname" : "3 star reviews",
"data": ThreeStarCounts
},
{
"seriesname" : "2 star reviews",
"data" : TwoStarCounts
},
{
"seriesname" : "1 star reviews",
"data": OneStarCounts
}
];
console.log(dataset); //<-- **dataset is printed here**
var response = {
"dataset" : dataset
};
obj['dataset'] = dataset;
console.log(obj);
res.send(obj);
mongoose.disconnect();
});
当我运行上面的Node.JS Express代码时,我得到console.log(dataset)
的输出为
[ { seriesname: 'Total positive reviews', data: [] },
{ seriesname: '5 star reviews', data: [] },
{ seriesname: '4 star reviews', data: [] },
{ seriesname: '3 star reviews', data: [] },
{ seriesname: '2 star reviews', data: [] },
{ seriesname: '1 star reviews', data: [] } ]
我的本地MongoDB集合中有数据&product;产品资讯&#39;但是没有数据被提取到光标中。
console.log(cursor)
中显示的My Aggregation游标如下:
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'sellerrank.product_reviews',
cmd:
{ aggregate: 'product_reviews',
pipeline: [ [Object], [Object] ],
allowDiskUse: true,
cursor: { batchSize: 100 } },
options:
{ allowDiskUse: true,
cursor: { batchSize: 100 },
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], define: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
disconnectHandler: Store { s: [Object], length: [Getter] } },
topology:
Server {
domain: null,
_events:
{ reconnect: [Function: reconnectHandler],
reconnectFailed: [Function: reconnectFailedHandler],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function],
timeout: [Function],
error: [Object],
close: [Function],
destroy: [Function: destroyHandler] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: BSON {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1,
serverDescription: [Object],
topologyDescription: [Object] },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2017-10-02T14:21:27.032Z,
maxWireVersion: 5,
minWireVersion: 0,
readOnly: false,
ok: 1 },
lastIsMasterMS: 12,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 5621,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null },
initalConnect: false,
wireProtocolHandler: WireProtocol { legacyWireProtocol: WireProtocol {} },
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.11.3, LE, mongodb-core: 2.1.15' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ aggregate: 'product_reviews',
pipeline: [Object],
allowDiskUse: true,
cursor: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 100,
currentLimit: 0,
transforms: undefined },
logger: Logger { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ maxTimeMS: null,
state: 0,
streamOptions: {},
bson: BSON {},
ns: 'sellerrank.product_reviews',
cmd:
{ aggregate: 'product_reviews',
pipeline: [Object],
allowDiskUse: true,
cursor: [Object] },
options:
{ allowDiskUse: true,
cursor: [Object],
promiseLibrary: [Function: Promise],
cursorFactory: [Object],
disconnectHandler: [Object] },
topology:
Server {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 12,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: [Object],
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
auto_reconnect: true,
clientInfo: [Object],
forceServerObjectId: false,
w: 1,
promiseLibrary: [Function: Promise],
bson: BSON {} },
promiseLibrary: [Function: Promise] },
sortValue: undefined,
eachAsync: [Function] }