鍍金池/ 問答/數(shù)據(jù)庫  HTML/ 如何使用nodejs操作MongoDB插入數(shù)據(jù)?

如何使用nodejs操作MongoDB插入數(shù)據(jù)?

問題描述

使用官方的例子,(一開始使用別的例子,試了很多都一樣),都無法插入數(shù)據(jù),如果數(shù)據(jù)庫不存在還會創(chuàng)建數(shù)據(jù)庫,但好像創(chuàng)建不了集合。

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

  1. 確定MongoDB是有開著的。
  2. 數(shù)據(jù)庫能被創(chuàng)建,而集合貌似沒被創(chuàng)建(因為這樣數(shù)據(jù)才沒插入?)

一開始是使用菜鳥教程里面的寫法,不行后又繼續(xù)百度,結(jié)果發(fā)現(xiàn)有中文社區(qū),用了里面的例子也不行(中文社區(qū)的例子和官網(wǎng)的差不多),之后翻墻去看官網(wǎng),用里面的例子也不行。

相關代碼

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

const url = 'mongodb://127.0.0.1:27017';//因為host文件改過,所以使用這個url

const dbName = 'myproject';

//插入文檔函數(shù)
const insertDocuments = function(db,callback) {
    const collection = db.collection('documents');
    collection.insertMany([
        { a: 1 }, { a: 3 }, { a: 2 }
    ],function(err,result) {
        assert.equal(err,null);
        assert.equal(3,result.result.n);
        assert.equal(3, result.ops.length);
        console.log('插入3條數(shù)據(jù)');
        callback(result);
    })
}

MongoClient.connect(url,function(err,client) {
    assert.equal(null,err);
    console.log('開啟服務器');
    const db = client.db(dbName);
    insertDocuments(db,function() {
        client.close();
    })
    
})

補充圖片:shell

謝謝各位大佬的回答,小弟感激不盡……想知道到底是哪個環(huán)節(jié)出錯了。

回答
編輯回答
祉小皓

你在robo 3T里查文檔的方法錯了,嘗試

show dbs
use myproject 
show collections

在用db.文檔名.find()前,需要用use指定是哪個db

2017年10月21日 17:04