Nodejs - 在js文件中连接到mongodb数据库?

时间:2022-10-04 12:54:07

So i have been looking at how to use mongodb from this tutorial: http://doduck.com/node-js-mongodb-hello-world-example/

所以我一直在研究如何使用本教程中的mongodb:http://doduck.com/node-js-mongodb-hello-world-example/

I have installed mongodb locally within my project folder that contains my html css and js, i run npm list mongodb within the project folder and i get the mongodb version. I haven't installed it globablly, but as far as i know that is ok right?

我在我的项目文件夹中本地安装了mongodb,其中包含我的html css和js,我在项目文件夹中运行npm list mongodb,我得到了mongodb版本。我没有全球安装,但据我所知,这是对的吗?

Anyways, i tried adding the example from the tutorial to test connect to a mongodb database. I just created a function and called it as soon as my page loads:

无论如何,我尝试添加教程中的示例来测试连接到mongodb数据库。我刚创建了一个函数,并在我的页面加载后立即调用它:

function connectMongo(){
    alert("test1");
    var MongoClient = require('mongodb').MongoClient;
    alert("test2");
    var myCollection;
    var db = MongoClient.connect('mongodb://127.0.0.1:27017/test',          function(err, db) {
    if(err){
        throw err;
        alert("mongoerror");
    }
    alert("connected to the mongoDB !");
   // myCollection = db.collection('test_collection');
});

}

}

The first test alert works, but the second test does not appear. However, the rest of the code on the page still runs, so i dont think there is a syntax error. I have no idea how exactly im meant to run this example, can anyone tell me why my function is exiting after the line

第一个测试警报有效,但第二个测试没有出现。但是,页面上的其余代码仍然运行,所以我不认为存在语法错误。我不知道我的意思是如何运行这个例子,任何人都可以告诉我为什么我的功能在线后退出

var MongoClient = require('mongodb').MongoClient;

I also have mongoose installed, even though im not quite sure if im even using it in my example here

我也安装了mongoose,即使我不太确定我是否甚至在我的例子中使用它

Sorry if my question is kind of vague, i have honestly no idea what im doing here

对不起,如果我的问题有点模糊,我真的不知道我在这做什么

2 个解决方案

#1


2  

First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.

首先,虽然Nodejs是用Javascript编写的,但您必须清楚地区分客户端和服务器功能。 Javascript的alert()对于在浏览器上弹出消息很有用。这不是Nodejs所做的事情,因为它是一个服务器应用程序。

Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.

忘记警报(“消息”);你想使用console.log(“message”);在服务器控制台上查看日志信息。

Prerequisite

条件

Let's quickly review Client-Server web interactions:

让我们快速查看客户端 - 服务器Web交互:

  1. Server is up and running
  2. 服务器已启动并正在运行
  3. Client Requests page via browser
  4. 客户端请求页面通过浏览器
  5. Page shows up on the client's browser
  6. 页面显示在客户端的浏览器上

Nodejs  - 在js文件中连接到mongodb数据库?

Step 1

步骤1

The missing step for you is (1), because the server is not up and running. This is done by typing the following on your terminal:

缺少的步骤是(1),因为服务器没有启动并运行。这可以通过在终端上键入以下内容来完成:

$ node name_of_file_here.js

If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.

如果语法中存在错误或缺少依赖项,控制台将记录错误。如果没有,那么一切都应该是好的。

Step 2

第2步

Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients. Some code needs to be added:

现在,在这一点上,您仍然不能指望在浏览器上看到任何“相关”,因为您的服务器虽然设置了MongoDB实例,但仍然没有收听来自客户端的请求。需要添加一些代码:

'use strict'; 
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

//Create a server
var server = http.createServer(function(request, response) {
    console.log("received request");  

    // use MongoClient to get relevant data 
    // var relevant_data = ...; 
    // response.write(relevant_data); 

    response.write("hey there"); 
    response.end(); 
}); 

server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

Final Note

最后的说明

I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.

我绝不是MongoDB大师,但我相信必须在您的系统上运行mongodb服务(服务器)才能使MongoDB客户端能够创建连接。

#2


1  

It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.

听起来你正试图在浏览器中运行mongo连接javascript。 mongodb连接通过节点可执行文件在服务器上运行。所以这是运行服务器端的Web应用程序中的javascript代码,而不是由Web应用程序传送到浏览器以运行客户端的javascript。

Create a file test.js

创建一个test.js文件

function connectMongo(){
  var MongoClient = require('mongodb').MongoClient;
  console.log('MongoClient is',typeof MongoClient)
  var myCollection;
  var url = 'mongodb://127.0.0.1:27017/test';
  var db = MongoClient.connect(url, function(err, db) {
    if(err){
      console.log("mongoerror", err);
      throw err;
    }
    console.log("connected to the mongoDB!");
    myCollection = db.collection('test_collection');
  });
}
connectMongo()

Then on your system, at a command or shell prompt, run

然后在您的系统上,在命令或shell提示符下运行

node test.js

It should print

它应该打印

$ node test.js
MongoClient is function
connected to the mongoDB!
^C

Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO

将服务器连接到数据库后,您可以将消息从前端javascript传递到后端服务器代码。通常这是通过Ajax http请求完成的,因此您的javascript会在后台发出额外的HTTP请求。 JQuery客户端库为此提供了一个简单的跨浏览器API。您还可以使用Websockets通过SocketIO从服务器来回传递消息

For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

有关Node / Express / MongoDB应用程序的基础知识,请尝试以下方法:http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

#1


2  

First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.

首先,虽然Nodejs是用Javascript编写的,但您必须清楚地区分客户端和服务器功能。 Javascript的alert()对于在浏览器上弹出消息很有用。这不是Nodejs所做的事情,因为它是一个服务器应用程序。

Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.

忘记警报(“消息”);你想使用console.log(“message”);在服务器控制台上查看日志信息。

Prerequisite

条件

Let's quickly review Client-Server web interactions:

让我们快速查看客户端 - 服务器Web交互:

  1. Server is up and running
  2. 服务器已启动并正在运行
  3. Client Requests page via browser
  4. 客户端请求页面通过浏览器
  5. Page shows up on the client's browser
  6. 页面显示在客户端的浏览器上

Nodejs  - 在js文件中连接到mongodb数据库?

Step 1

步骤1

The missing step for you is (1), because the server is not up and running. This is done by typing the following on your terminal:

缺少的步骤是(1),因为服务器没有启动并运行。这可以通过在终端上键入以下内容来完成:

$ node name_of_file_here.js

If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.

如果语法中存在错误或缺少依赖项,控制台将记录错误。如果没有,那么一切都应该是好的。

Step 2

第2步

Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients. Some code needs to be added:

现在,在这一点上,您仍然不能指望在浏览器上看到任何“相关”,因为您的服务器虽然设置了MongoDB实例,但仍然没有收听来自客户端的请求。需要添加一些代码:

'use strict'; 
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

//Create a server
var server = http.createServer(function(request, response) {
    console.log("received request");  

    // use MongoClient to get relevant data 
    // var relevant_data = ...; 
    // response.write(relevant_data); 

    response.write("hey there"); 
    response.end(); 
}); 

server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

Final Note

最后的说明

I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.

我绝不是MongoDB大师,但我相信必须在您的系统上运行mongodb服务(服务器)才能使MongoDB客户端能够创建连接。

#2


1  

It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.

听起来你正试图在浏览器中运行mongo连接javascript。 mongodb连接通过节点可执行文件在服务器上运行。所以这是运行服务器端的Web应用程序中的javascript代码,而不是由Web应用程序传送到浏览器以运行客户端的javascript。

Create a file test.js

创建一个test.js文件

function connectMongo(){
  var MongoClient = require('mongodb').MongoClient;
  console.log('MongoClient is',typeof MongoClient)
  var myCollection;
  var url = 'mongodb://127.0.0.1:27017/test';
  var db = MongoClient.connect(url, function(err, db) {
    if(err){
      console.log("mongoerror", err);
      throw err;
    }
    console.log("connected to the mongoDB!");
    myCollection = db.collection('test_collection');
  });
}
connectMongo()

Then on your system, at a command or shell prompt, run

然后在您的系统上,在命令或shell提示符下运行

node test.js

It should print

它应该打印

$ node test.js
MongoClient is function
connected to the mongoDB!
^C

Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO

将服务器连接到数据库后,您可以将消息从前端javascript传递到后端服务器代码。通常这是通过Ajax http请求完成的,因此您的javascript会在后台发出额外的HTTP请求。 JQuery客户端库为此提供了一个简单的跨浏览器API。您还可以使用Websockets通过SocketIO从服务器来回传递消息

For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

有关Node / Express / MongoDB应用程序的基础知识,请尝试以下方法:http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/