美文网首页
MongoDB 之大坑

MongoDB 之大坑

作者: 你只是个Baby | 来源:发表于2017-12-12 15:24 被阅读42次

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

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

仅仅当做给自己留个笔记

相关文章

网友评论

      本文标题:MongoDB 之大坑

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