节点JS:没有插入到mongodb中
所以我在tutsplus.com上学了一个Node.js教程,直到现在,这个教程都很棒。
我正在关于MongoDB的教训,而且我已经有点失落了。 我不知道为什么这对我不起作用,因为它在video中工作,我的代码是相同的。 我所能想到的是,自从一年前的课程以来,有了一个更新。
从尝试console.log
在不同的地方,我认为数据是不是在开始正确插入,所以没有任何返回。
除了cursor.toArray()
的callback之外,一切似乎都按预期启动。
我现在正在学习node和mongodb,所以如果我犯了一个明显的错误,请耐心等待。
我被指示写下面的文件,然后在命令行中执行它。
编辑:
我已经把问题缩小到插入脚本。 当通过CLI插入数据时,它会将其恢复。
var mongo = require('mongodb'), host = "127.0.0.1", port = mongo.Connection.DEFAULT_PORT, db = new mongo.Db('nodejsintro', new mongo.Server(host, port, {})); db.open(function(err){ console.log("We are connected! " + host + " : " + port); db.collection("user", function(error, collection){ console.log(error); collection.insert({ id: "1", name: "Chris Till" }, function(){ console.log("Successfully inserted Chris Till") }); }); });
你确定你真的连接到mongo? 当你从cli连接到mongo并键入'show dbs'时,你看到nodejsintro? 收集是否存在?
另外,从你的代码
db.open(function(err){ //you didn't check the error console.log("We are connected! " + host + " : " + port); db.collection("user", function(error, collection){ //here you log the error and then try to insert anyway console.log(error); collection.insert({ id: "1", name: "Chris Till" }, function(){ //you probably should check for an error here too console.log("Successfully inserted Chris Till") }); }); });
如果您已经调整了日志logging并确保您没有收到任何错误,那么我们尝试更改一些连接信息。
var mongo = require('mongodb'); var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('nodejsintro', server); db.open(function(err, db) { if (!err) { console.log("Connected to 'nodejsintro' database"); db.collection('user', {strict: true}, function(err, collection) { if (err) { console.log("The 'user' collection doesn't exist. Creating it with sample data..."); //at this point you should call your method for inserting documents. } }); } });