简体   繁体   English

如何将mongodb与Node.js正确连接?

[英]How do I connect mongodb with Node.js correctly?

Hi I've been trying to get this code to work but I could not figure out what's wrong with my code. 嗨,我一直在尝试使此代码正常工作,但我无法弄清楚我的代码有什么问题。 It should have printed "here..." if the connection is open. 如果连接打开,它应该已经打印了“ here ...”。 Also, I look at the console of "mongod" it shows there's a connection opened but nothing prints out. 另外,我看一下“ mongod”的控制台,它显示有打开的连接,但没有任何输出。


var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('test1', new Server('127.0.0.1', 27017, {}));


var Vocabulary = function() {

    function get(german_vocab) {
        client.open(function(err, pClient) {
            console.log("here...")
            client.collection('test1', function(err, collection) {
                collection.insert({name:"myself"});
            });

            client.collection.find().toArray(function(err, results) {
                console.log(results);
            });
        });

    }

    return {
        get : get
    };
}

module.exports = Vocabulary;


var vocab = Vocabulary();
vocab.get("Ich"); // Nothing shows in this line. 

Also when I check there's no database created as well. 另外,当我检查时,也没有创建数据库。 I thought that mongodb database is lazily created once there's something inserted? 我以为一旦插入某些内容,就会延迟创建mongodb数据库?

Thanks a lot. 非常感谢。

In the docs they describe a function called db.createCollection([[name[, options]], callback) , have you tried that? 他们在文档中描述了一个名为db.createCollection([[name[, options]], callback)的函数,您是否尝试过? And maybe you should think about using something like mongoose , which is a nice 3rd party lib for working with mongodb. 也许你应该考虑使用类似猫鼬 ,这是与MongoDB的工作一个很好的第三方库。

I hope I could help! 希望我能帮上忙! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM