安装“mongodb”npm模块。它是NodeJs的官方MongoDB客户端。
// Create a Mongo Client Instace to connect to the MongoDB Database
// and perform various functions.
const MongoClient = require( 'mongodb' ).MongoClient;
// Store the URL of your MongoDB Server
const mongoURL = "mongodb://localhost:27017/";
// Stored the name of the Database you wanna connect to.
const dbName = "testdb";
// Create a new Mongo DB client that will connect to the MongoDB Server.
const client = new MongoClient(mongoURL);
// Connect the Client to the MongoDB Server.
client.connect( (err) => {
// Error handling of some sort.
if(err) throw err;
console.log( 'connected!' );
// Connect to the database you want to manage using the dbName you
// stored earlier.
const db = client.db( dbName );
// Store the name of the collection you want to read from.
// this can be created above near the dbName.
const collectionName = "testCol"
// Connect to the collection that you stored above.
const collection = db.collection( collectionName );
// Query the MongoDB database and log the results, if any.
collection.find({}).toArray( (err, docs) => {
console.log(docs);
} );
} )
const client = new MongoClient( mongoURL, { useNewUrlParser: true } );
而不是
const client = new MongoClient(mongoURL);
http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/