Koa操作Mongodb

274 阅读1分钟

1原生nodejs操作Mongodb

mongodb.github.io/node-mongod…

看最新版本的reference以及api

First, create a directory where your application will live.

mkdir myproject 
cd myproject

Enter the following command and answer the questions to create the initial structure for your new project:

npm init

Next, install the driver dependency.

npm install mongodb --save

Create a database directory (in this case under /data).

nstall and start a mongod process.

mongod --dbpath=/data

Connect to MongoDB

Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.

Add code to connect to the server and the database myproject:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
}); 

Run your app from the command line with:

node app.js

mongodb.github.io/node-mongod…

mongodb.github.io/node-mongod…

2.koa封装mongodb连接