美文网首页
node操作mongodb

node操作mongodb

作者: 阿水日记 | 来源:发表于2018-11-27 10:55 被阅读0次

http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/

一、安装使用mongodb库

  1. 安装
    npm install mongodb --save
  2. 引入 mongodb 下的MongoClient
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
  3. 定义数据库连接的地址以及配置数据库名称
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';
  1. nodejs连接数据库
// 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();
});
  1. 操作
const collection = db.collection('documents');
  // Insert some documents
  collection.insertMany([
    {a : 1}, {a : 2}, {a : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });

相关文章

网友评论

      本文标题:node操作mongodb

      本文链接:https://www.haomeiwen.com/subject/wvtyqqtx.html