How do I connect to mongodb with node.js (and authenticate)?

How do I connect to mongodb with node.js?

I have the node-mongodb-native driver.

There's apparently 0 documentation.

Is it something like this?

var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});

Where do I put the username and the password?

Also how do I insert something?

Thanks.

115252 次浏览

Per 源头:

连接后:

Db.authenticate(user, password, function(err, res) {
// callback
});

如果你继续与当地司机有问题,你也可以检查困倦的猫鼬。它是一个 python REST 服务器,您可以通过节点请求访问它,以访问您的 Mongo 实例。 http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/

我推荐我刚刚创建的 猫皮

var mongo = require('mongoskin');
var db = mongo.db('admin:pass@localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});

猫皮是同步的吗? 不,它是异步的。

这对我很有效:

Db.admin().authenticate(user, password, function() {} );

你可以这样做

var db = require('mongo-lite').connect('mongodb://localhost/test')

更多细节。

Slight typo with Chris' answer.

Db.authenticate(user, password, function({ // callback }));

应该是

Db.authenticate(user, password, function(){ // callback } );

另外,根据您的 mongodb 配置,您可能需要先连接到 admin 和 auth,然后再转到其他数据库。如果您不向试图访问的数据库添加用户,就会出现这种情况。然后您可以通过管理员进行授权,然后切换数据库,然后随意进行读写操作。

我发现使用 Mongo 网址很方便。我将 URL 存储在一个环境变量中,并使用它来配置服务器,而开发版本使用一个没有密码的默认 URL。

网址的格式如下:

export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME

以这种方式连接的代码:

var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;


mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {


if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});

每个人都应该使用这个来源链接:

http://mongodb.github.com/node-mongodb-native/contents.html

回答这个问题:

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,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');


var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});


// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);


// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);


// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);


db.close();
});
});
});

通过@mattdlockyer 提供的链接作为参考,这对我很有用:

var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});


exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};

我在用猫鼬连接到蒙哥布。 使用以下命令安装猫鼬 npm

安装猫鼬

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);

我们可以像这样使用查询

user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});

我的版本是:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass@dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'@'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');


}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');


}
});

这里是新的可以从“管理”认证,然后切换到您想要的数据库进行进一步的操作:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');


var user = 'user';
var password = 'password';


MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});


db.close();


});
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'


// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);


// Database Name
const dbName = 'myProject';


async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');


// the following code examples can be pasted here...


return 'done.';
}


main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());

您可以在这里的文档中找到更多内容: https://mongodb.github.io/node-mongodb-native/4.1/