通过 Node.js 插入 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5669321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert into MongoDB via Node.js
提问by Tom
I am new to both Node.js and MongoDB, but I intend to create a very basic real time geolocation based web app. Here is my attempt at figuring out how Node and MongoDB interact:
我是 Node.js 和 MongoDB 的新手,但我打算创建一个非常基本的基于实时地理定位的 Web 应用程序。这是我试图弄清楚 Node 和 MongoDB 如何交互的尝试:
var mongo = require('mongodb');
var db = new mongo.Db('test', new mongo.Server('localhost',22892, {}), {});
db.open(function(){});
db.collection('docs', function(err,collection){
doc = {"foo":"bar"};
collection.insert(doc, function(){});
});
I can see that this is connecting:
我可以看到这是连接:
Thu Apr 14 15:24:12 [initandlisten] connection accepted from 127.0.0.1:46968 #26
Thu Apr 14 15:24:12 [conn26] building new index on { _id: 1 } for test.docs
Thu Apr 14 15:24:12 [conn26] done for 0 records 0secs
But it's not inserting any documents into the database. Can anyone tell me what I am doing wrong?
但它没有将任何文档插入数据库。谁能告诉我我做错了什么?
Thanks
谢谢
回答by Raynos
db.open(function(err, client){
client.createCollection("docs", function(err, col) {
client.collection("docs", function(err, col) {
for (var i = 0; i < 100; i++) {
col.insert({c:i}, function() {});
}
});
});
});
You forgot to do everything in your opencallback. This is important otherwise your code runs before your connection to the database is open. You have to do everything asynchronous. It's also best to create the collection if it does not exist.
您忘记在open回调中执行所有操作。这很重要,否则您的代码会在与数据库的连接打开之前运行。您必须异步执行所有操作。如果集合不存在,最好也创建它。
Take a look at the extensive examples at the github page
查看github 页面上的大量示例
Now this looks like callback spaghetti so we use flowcontrol like Stepto make it pretty.
现在这看起来像回调意大利面,所以我们使用 flowcontrolStep让它变得漂亮。
Step(
function() {
db.open(this);
},
function(err, client) {
client.createCollection("docs", this);
},
function(err, col) {
for (var i = 0; i < 100; i++) {
col.insert({c:i});
}
}
);

