通过Node.js插入MongoDB [英] Insert into MongoDB via Node.js

查看:88
本文介绍了通过Node.js插入MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js和MongoDB的新手,但是我打算创建一个非常基本的基于实时地理位置的Web应用程序.这是我尝试弄清Node和MongoDB如何交互的尝试:

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:

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?

谢谢

推荐答案

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() {});
             }
         });
    });
});

您忘记了执行open回调中的所有操作.这很重要,否则在打开与数据库的连接之前,您的代码将运行.您必须异步进行所有操作.如果集合不存在,最好也创建它.

You forgot to do everything in your open callback. 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.

github页面

现在,这看起来像是回调意大利面条,因此我们使用 Step 之类的流程控制来使其美观.

Now this looks like callback spaghetti so we use flowcontrol like Step to make it pretty.

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});
        }
    }
);

这篇关于通过Node.js插入MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆