rwuser and mongouser by default to support the MONGODB-CR and SCRAM-SHA-1 authentication methods, respectively. The connecting URIs for the two authentication methods are formed differently. For more information, please see Connection Sample.npm install mongodb --save(If the installation failed, you can try another source, such as `npm config set registry http://registry.cnpmjs.org`)npm init
'use strict';var mongoClient = require('mongodb').MongoClient,assert = require('assert');// Form the URIvar url = 'mongodb://mongouser:thepasswordA1@10.66.161.177:27017/admin';mongoClient.connect(url, function(err, db) {assert.equal(null, err);var db = db.db('testdb'); // Select a databasevar col = db.collection('demoCol'); // Select a collection (table)// Insert datacol.insertOne({a: 1,something: "yy"},// Optional parameters//{// w: 'majority' // Enable the "Majority" mode to ensure that data are written to the Secondary nodes//},function(err, r) {console.info("err:", err);assert.equal(null, err);// Assertion is written successfullyassert.equal(1, r.insertedCount);// Query datacol.find().toArray(function(err, docs) {assert.equal(null, err);console.info("docs:", docs);db.close();});});});
[root@VM_2_167_centos node]# node index.jsdocs: [ { _id: 567a1bf26773935b3ff0b42a, a: 1, something: 'yy' } ]
var dbUri = "mongodb://" + user + ":" + password + "@" + host + ":" + port + "/" + dbName;var opts = {auth: {authMechanism: 'MONGODB-CR', // This parameter is not required if SCRAM-SHA-1 authentication is usedauthSource: 'admin'}};var connection = mongoose.createConnection(dbUri, opts);
フィードバック