我正在尝试编写一段代码,以便使用' mongodb'从node.js连接到mongodb数据库。图书馆。
这里有一段代码描述了我想要实现的目标:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
assert = require('assert');
var User = require('mongo-bcrypt-user');
// Set up the connection to the local db
var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
var db = mongoclient.db("test");
var coll = db.collection('users');
尝试运行文件时遇到以下错误:
D:\mongodb.js:15
var db = mongoclient.db("test");
^
TypeError: undefined is not a function
at Object.<anonymous> (D:\Backups\C Drive New Backup\temp\mongodb.js:15:24)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (D:\Backups\C Drive New Backup\temp\MyWebAPI.js:8:20)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
提前致谢:]
答案 0 :(得分:2)
MongoClient
没有db
方法:http://mongodb.github.io/node-mongodb-native/2.0/api/MongoClient.html
它有connect(url, options, callback)
方法,其中callback
是connectCallback(error, db)
函数,因此您的代码必须如下所示:
var mongoclient = new MongoClient('mongodb://localhost:27017',
{native_parser: true},
function(error, db) {
// use db here
});
注意JavaScript中异步编程的概念。即回调和承诺。