草庐IT

javascript - 类型错误 : Object #<MongoClient> has no method 'db'

coder 2023-10-29 原文

我是 node.js、mongodb、express 的新手,在设置数据库时遇到了很多麻烦。我的代码(app.js)在下面给出

var express = require('express'),
    app = express(),
    cons = require('consolidate'),
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

    app.engine('html', cons.swig);
    app.set('view engine', 'html');
    app.set('views', __dirname + '/views');

var mongoclient = new MongoClient(new Server("localhost", 27017));
// error occurs here
var db = mongoclient.db('course');

app.get('/', function(req, res){  
   // Find one document in our collection
   db.collection('hello_combined').findOne({}, function(err, doc) {
      if(err) throw err;
      res.render('hello', doc);
   });
});

mongoclient.open(function(err, mongoclient) {
   if(err) throw err;
   app.listen(8080);
});

当我运行此代码 node app.js 时,出现以下错误:

sabbir@sabbir-pc:~/nodejs/hello_express$ node app.js

 /home/sabbir/nodejs/hello_express/app.js:12
 var db = mongoclient.db('course');
                      ^
 TypeError: Object #<MongoClient> has no method 'db'
   at Object.<anonymous> (/home/sabbir/nodejs/hello_express  /app.js:12:22)
   at Module._compile (module.js:456:26)
   at Object.Module._extensions..js (module.js:474:10)
   at Module.load (module.js:356:32)
   at Function.Module._load (module.js:312:12)
   at Function.Module.runMain (module.js:497:10)
   at startup (node.js:119:16)
   at node.js:935:3

注意:我使用的是 Ubuntu 14.04.02,我的 node.js 版本 v0.10.38MongoDB shell 版本:3.0.2

编辑 我还使用以下代码::

var mongoclient = new MongoClient(new Server("localhost", 27017));

mongoclient.open(function(err, mongoclient) {
  if(err) throw err;
  var db = mongoclient.db('course');

  app.get('*', function(req, res){
      res.send('Page Not Found', 404);
  });
  app.get('/', function(req, res){
    // Find one document in our collection
    db.collection('hello_combined').findOne({}, function(err, doc) {
       if(err) throw err;
       res.render('hello', doc);
    });
  });
  app.listen(8080);
});

我有以下错误::

 sabbir@sabbir-pc:~/nodejs/hello_express$ node app.js

 /home/sabbir/nodejs/hello_express/app.js:13
 mongoclient.open(function(err, mongoclient) {
             ^
 TypeError: Object #<MongoClient> has no method 'open'
    at Object.<anonymous> (/home/sabbir/nodejs/hello_express/app.js:13:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:935:3

最佳答案

如果想使用 MongoClient,它允许连接到 MongoDB,请按以下方式操作:

     var MongoClient = require('mongodb').MongoClient,
     test = require('assert');
     var url = 'mongodb://localhost:27017/test';
     Connect using MongoClient
     MongoClient.connect(url, function(err, db) {
     var testDb = db.db('test'); //use can chose the database here
     db.close();
    });

另一种方法:

但是,如果您想使用 express 并将变量与应用程序对象相关联并使用应用程序进行初始化,可以这样做:

var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
MongoServer = require('mongodb').Server,
Db = require('mongodb').Db,
db = new Db('pcat', new MongoServer('localhost', 27017, { 'native_parser': true }));

db.open(function (err, asdf) {
app.listen(8080);
console.log("The server is listening at port 8080");
});

*Package.json:

  • "合并":"^0.13.1",
  • "表达": "^3.4.4",
  • "mongodb": "^2.0.40",
  • “痛饮”:“^1.4.2”*

关于javascript - 类型错误 : Object #<MongoClient> has no method 'db' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29612474/

有关javascript - 类型错误 : Object #<MongoClient> has no method 'db'的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby-on-rails - Railstutorial : db:populate vs. 工厂女孩 - 2

    在railstutorial中,作者为什么选择使用这个(代码list10.25):http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-usersnamespace:dbdodesc"Filldatabasewithsampledata"task:populate=>:environmentdoRake::Task['db:reset'].invokeUser.create!(:name=>"ExampleUser",:email=>"example@railstutorial.org",:passwo

  5. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  6. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

随机推荐