使用 mongodb 遇到的db.collection is not a function
发布于 6 年前 作者 fairyly 7855 次浏览 来自 问答

TypeError: db.collection is not a function

之后在连接数据库回调中加入 var mydb = db.db(‘myDatabaseNameAsAString’); 参考:https://stackoverflow.com/questions/43779323/typeerror-db-collection-is-not-a-function https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html 不太清楚这么写是为什么?

具体代码: var MongoClient = require(‘mongodb’).MongoClient; var assert = require(‘assert’); var url = ‘mongodb://localhost:27017/test’; var insertDocument = function(db, callback) { db.collection(‘restaurants’).insertOne( { “address” : { “street” : “2 Avenue”, “zipcode” : “10075”, “building” : “1480”, “coord” : [ -73.9557413, 40.7720266 ] }, “borough” : “Manhattan”, “cuisine” : “Italian”, “grades” : [ { “date” : new Date(“2014-10-01T00:00:00Z”), “grade” : “A”, “score” : 11 }, { “date” : new Date(“2014-01-16T00:00:00Z”), “grade” : “B”, “score” : 17 } ], “name” : “Vella”, “restaurant_id” : “41704620” }, function(err, result) { assert.equal(err, null); console.log(“Inserted a document into the restaurants collection.”); callback(); }); }; // 连接数据库 MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log(‘Connected correctly to server.’,db); var mydb = db.db(‘myDatabaseNameAsAString’); // 插入数据 insertDocument(mydb, function() { db.close(); }); });

3 回复

看一下你的package.json mongodb是什么版本,上面的写法对应3.0以上

明白了我现在的 3.0 以上版本,原来 3.0 以下的写法 db.collection() 会报错 db.collection is not a function

所以你们去网上找demo的时候都不看下变量有没有赋值的么? var db = db.db(“myDB”);

回到顶部