我一直收到此错误Cannot call method 'insert' of undefined
,我无法理解原因。我正在按照教程进行操作,虽然我们的代码是相同的,但它不适合我。这是代码。
var mongo = require("mongodb");
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodejs-introduction", new mongo.Server(host, port, {}));
db.open(function(error) {
console.log("We are connected " + host + ":" + port);
db.collection("user", function(error, collection) {
console.log("We have the collection");
collection.insert({
id: "1",
name: "John Smith",
twitter: "johns",
}, function() {
console.log("Successfully inserted John");
});
collection.insert({
id: "2",
name: "Eric Cartman",
twitter: "cartman",
}, function() {
console.log("Successfully inserted Eric");
});
});
});
答案 0 :(得分:1)
您从未定义变量collection
,因此未定义。尝试console.log(collection);
检查这是否属实。我很惊讶本教程适用于某人。
要解决问题,只需使用以下代码定义您的收藏:var collection = db.collection('user');
答案 1 :(得分:0)
尝试使用它并查看它是否有效:
var collection = db.get('user');
collection.insert({
id: "1",
name: "John Smith",
twitter: "johns",
}, function() {
console.log("Successfully inserted John");
});