MongoDB 之大坑

记录一下这个大坑额,折腾的好几个小时。先看一段官方文档

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Get the collection
  var col = db.collection('insert_one');
  col.insertOne({a:1}, function(err, r) {
    test.equal(null, err);
    test.equal(1, r.insertedCount);
    // Finish up test
    db.close();
  });
});

然后你开心的去按照文档运行了,Duang,控制台飘出这个错误
我是截图.png

db.collection is not a function😓,真是日了狗了。
网上各种查找,翻了个把小时,找到个要降低mongoDb版本的回答,意思是降到2.?.?版本,然后就能用了!最后不死心,继续翻, 又一个小时过去了,终于被我翻到了,贴下成功的代码

MongoClient.connect('mongodb://localhost:27017/test',(err,client)=>{
    if(err){
        console.log(err);
        return;
    }
    console.log("数据库连接成功了");
   
    //主要是这两句
    var db = client.db("test");
    var collection = db.collection("person");
  
    //接下来就能执行插入操作了
    collection.insertOne({
        "name":"王小猫",
        "age":25
    },function(err,res){
        if (err){
            console.log(err);
            return;
        }     
    });
});

仅仅当做给自己留个笔记

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容