美文网首页
node封装后操作mongodb

node封装后操作mongodb

作者: 范er_er | 来源:发表于2019-11-05 10:09 被阅读0次

<meta charset="utf-8">

<article class="_2rhmJa">

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);
  });

</article>

相关文章

网友评论

      本文标题:node封装后操作mongodb

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