Chr*_*ill 5 javascript mongodb node.js
所以我正在学习 tutsplus.com 上的Node.js教程课程,到目前为止它一直很棒。
我正在学习关于 MongoDB 的课程,但我有点不知所措。我不确定为什么这对我不起作用,因为它在视频中起作用并且我的代码是相同的。我所能想到的是,自从一年前开设课程以来,已经有了更新。
从尝试到console.log各个点,我认为数据在开始时没有正确插入,因此没有返回任何内容。
除了cursor.toArray().
我目前正在学习 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")
});
});
});
Run Code Online (Sandbox Code Playgroud)
你确定你确实连接到了 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")
});
});
});
Run Code Online (Sandbox Code Playgroud)
如果您已经调整了日志记录并且确定没有收到任何错误,那么让我们尝试更改一些连接信息。
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.
}
});
}
});
Run Code Online (Sandbox Code Playgroud)