02_使用Node.js往mongodb插入資料

來源:互聯網
上載者:User

標籤:log   data   div   cmd   cal   enc   mod   斜杠   depend   

上節課學習了如何使用Node.js串連資料庫,這節課我們學習如何插入資料。

1、採用node.js串連MongoDB資料成功之後,想在資料庫中寫入資料,卻顯示db.collection不是一個函數。test.js代碼如下:

var express = require("express");var  app = express();var MongoClient = require(‘mongodb‘).MongoClient;var  assert = require(‘assert‘);//用於調試資訊// Connection URLvar url = ‘mongodb://localhost:27017/stu‘;//串連地址,斜杠"/myproject"表示資料庫,若不存在則自動建立app.get("/",function(req,res){ MongoClient.connect(url, function(err, db) { // Use connect method to connect to the server   //回呼函數表示串連成功之後做的事情,db是串連上的資料庫實體。     if(err){ // assert.equal(null, err);將err和null進行比較,如若err==null相等,表示資料庫連接成功。       console.log("資料庫連接失敗");       return;     }      console.log("Connected successfully to server");      insertDocuments(db,function(result){console.log(result); });       });   res.send("你好啊");});app.listen(3000);var insertDocuments = function(db, callback) {  // Get the myTestDataBase collection   db.collection(‘myTestDataBase‘).insertOne([    {"hahaha" : 1}   ], function(err, result) {     console.log("Inserted 3 documents into the collection");    callback(result);    db.close();  });}

在cmd中運行命令:node test.js,控制台報錯如下:

2、解決辦法(參考:https://segmentfault.com/q/1010000012306610)

這個錯誤是出在mongodb的庫中,只需要把node_modules中mongodb的版本換為2.3.33vision即可解決;

"dependencies": {"mongodb": "^2.2.33"}

然後:

npm install

3、再次運行node test.js

02_使用Node.js往mongodb插入資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.