gpt4 book ai didi

javascript - TypeError : dbObject.集合不是函数

转载 作者:行者123 更新时间:2023-12-03 01:10:09 24 4
gpt4 key购买 nike

我正在尝试从数据库中获取数据,但卡在某个点上。我收到此错误,但我不知道出了什么问题。我试图找到解决方案但仍然没有得到适当的答案。我正在尝试从本教程中实现它。

https://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/creating-interactive-charts-using-node-express-and-mongodb

这是我的代码:

//import express package
var express = require("express");

//import mongodb package
var mongodb = require("mongodb");

//MongoDB connection URL - mongodb://host:port/dbName
var dbHost = "mongodb://localhost:27017/fusion_demo";

//DB Object
var dbObject;

//get instance of MongoClient to establish connection
var MongoClient = mongodb.MongoClient;

//Connecting to the Mongodb instance.
//Make sure your mongodb daemon mongod is running on port 27017 on localhost
MongoClient.connect(dbHost, function(err, db){
if ( err ) throw err;
dbObject = db;
console.log('connect to server');
// console.log(db);
});

function getData(responseObj){
//use the find() API and pass an empty query object to retrieve all records
dbObject.collection("fuel_price").find({}).toArray(function(err, docs){
if ( err ) throw err;
var monthArray = [];
var petrolPrices = [];
var dieselPrices = [];

for ( index in docs){
var doc = docs[index];
//category array
var month = doc['month'];
//series 1 values array
var petrol = doc['petrol'];
//series 2 values array
var diesel = doc['diesel'];
monthArray.push({"label": month});
petrolPrices.push({"value" : petrol});
dieselPrices.push({"value" : diesel});
}

var dataset = [
{
"seriesname" : "Petrol Price",
"data" : petrolPrices
},
{
"seriesname" : "Diesel Price",
"data": dieselPrices
}
];

var response = {
"dataset" : dataset,
"categories" : monthArray
};
responseObj.json(response);
});
}

//create express app
var app = express();

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs = require('express-handlebars');

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

//Defining middleware to serve static files
app.use('/public', express.static('public'));
app.get("/fuelPrices", function(req, res){
getData(res);
});
app.get("/", function(req, res){
res.render("chart");
});

app.listen("3300", function(){
console.log('Server up: http://localhost:3300');
});

最佳答案

dbObject 为 null,因此没有收集方法。可能 Mongo DB 未运行或正在不同的端口中运行。检查 MongoDB 是否正确启动并运行,并且您可以连接到它。

关于javascript - TypeError : dbObject.集合不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231918/

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