简体   繁体   中英

How to work with node.js and mongoDB

I read :

And I am really confused. How I should work with mongoDB from node.js? I'm a rookie, and my question may look stupid.

var db = new db.MongoClient(new db.Server('localhost', 27017));
    db.open(function(err, dataBase) {
       //all code here?
       dataBase.close();
    });

Or every time when I needing something from db I need call:

MongoClient.connect("mongodb://localhost:27017/myDB", function(err, dataBase) {
    //all code here 
    dataBase.close();
});

What is the difference betwen open and connect? I read in the manual that open: Initialize and second connect. But what exactly does that mean? I assume that both do the same, but in the other way, so when should I use one instead the other?

I also wanna ask it's normal that mongoClient needing 4 socket? I running two myWEbServer at the same time, here's picture: http://i43.tinypic.com/29mlr14.png

EDIT: I wanna mention that this isn't a problem ( rather doubt :D), my server works perfect. I ask because I wanna know if I am using mongoDB driver correctly. Now/Actually I use first option,init mongo dirver at the beginning and inside load put all code.

I'd recommend trying the MongoDB tutorial they offer. I was in the same boat, but this breaks it down nicely. In addition, there's this article on github that explains the basics of DB connection.

In short, it does look like you're doing it right.

MongoClient.connect("mongodb://localhost:27017/myDB", function(err, dataBase) {
    //all code here 
    var collection = dataBase.collection('users');
    var document1 = {'name':'John Doe'};
    collection.insert(document1, {w:1}, function(err,result){
        console.log(err);
    });
    dataBase.close();
});

You still can sign up for a free course M101JS: MongoDB for Node.js Developers , provided by MongoDB guys

Here is short description:

This course will go over basic installation, JSON, schema design, querying, insertion of data, indexing and working with language drivers. In the course, you will build a blogging platform, backed by MongoDB. Our code examples will be in Node.js.

I had same question. I couldn't find any proper answer from mongo documentation. All document say is to prefer new db connection and then use open (rather than using connect() ) http://docs.mongodb.org/manual/reference/method/connect/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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