02_使用Node.js往mongodb插入数据
                        
                            时间:2021-07-01 10:21:17
                            帮助过:3人阅读
							                        
                     
                    
                    
                     express = require("express"
);
var  app =
 express();
var MongoClient = require(‘mongodb‘
).MongoClient;
var  assert = require(‘assert‘);
//用于调试信息
// Connection URL
var 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插入数据
标签:log   data   div   cmd   cal   enc   mod   斜杠   depend