简体   繁体   English

如何在不使用框架的情况下通过Node.js将数据从MongoDB显示到前端

[英]How to display data from MongoDB to the frontend via Node.js without using a framework

I am new to Node.js and programming in general. 我是Node.js和一般编程的新手。 This is my first server side language and I need your help. 这是我的第一种服务器端语言,需要您的帮助。 I do have html/css/javascript experience. 我确实有html / css / javascript经验。 I also know how to serve up html pages via NodeJS using FileSystem and the request.url stream. 我也知道如何使用FileSystem和request.url流通过NodeJS提供html页面。

*Question:* How do you query and display data from Mongo DB into an html page without using Express or any other framework? *问题:*您如何在不使用Express或任何其他框架的情况下,将Mongo DB中的数据查询并显示到html页面中? Pure Node.JS /Javascript** 纯Node.JS / Javascript **

I rather not use Express because I am trying to master Node.JS first. 我宁愿不使用Express,因为我要先掌握Node.JS。

I tried studying PHP's way of doing it, and found their process to to be like this : 我尝试研究PHP的实现方式,发现他们的过程像这样:

Connect to database: 连接到数据库:

$con=mysqli_connect("example.com","peter","abc123","my_db");

Query Database: 查询数据库:

$result = mysql_query("SELECT * FROM names");

Display Results : 显示结果:

<?php echo $result; ?>

How does Node.js connect / query / and display from database to front end? Node.js如何连接/查询/并从数据库显示到前端? without using frameworks like EXPRESS 无需使用EXPRESS之类的框架

To query mongo with node you are most definetly going to need some sort of node-module such as node-mongo-db-native ( https://github.com/mongodb/node-mongodb-native ). 要使用node查询mongo,您最明确地将需要某种节点模块,例如node-mongo-db-native( https://github.com/mongodb/node-mongodb-native )。 You can't do it with just node core... 您不能仅凭节点核心来做到这一点...

Here is an example of querying a mongodb using node-mongo-db-native module docs... 这是一个使用node-mongo-db-native模块文档查询mongodb的示例...

var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('test_insert');
    collection.insert({a:2}, function(err, docs) {

      collection.count(function(err, count) {
        console.log(format("count = %s", count));
      });

      // Locate all the entries using find
      collection.find().toArray(function(err, results) {
        console.dir(results);
        // Let's close the db
        db.close();
      });
    });
  })

Try this example, it contains one route ( http://localhost:3000/test ) which you can request from your frontend and it will return json data taken from the mongodb using mongoose. 试试这个例子,它包含一个可以从前端请求的路由( http:// localhost:3000 / test ),它将使用mongoose返回从mongodb获取的json数据。

Test.js Test.js

var express = require("express"),
    app = express(),
    bodyparser = require("body-parser"),
    mongoose = require("mongoose");

const router = express.Router();

app.use(bodyparser.json());

mongoose.connect('mongodb://localhost:27017/test');

const connection = mongoose.connection;

connection.once('open', () => {
    console.log('MongoDB connected successfully');
})

var schema = new mongoose.Schema({
    name: String,
    value: String
})

var data=mongoose.model("testdata", schema);

router.route('/test').get((req, res) => {
    data.find((err, testdata) => {
        if (err)
            console.log(err)
        else
            res.json(testdata);

    })
})


    app.use('/', router);



    app.listen(3000, function () {
        console.log('server started on port 3000');
    });

here is my code which I have run in my localhost, and it is working fine. 这是我在本地主机上运行的代码,它工作正常。

Code

const http = require('http');
const port = 8080;
const hostname = 'localhost';

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testDB', {
   useCreateIndex: true,
   useNewUrlParser: true
});

var schema = new mongoose.Schema({
   firstName: String,
   lastName: String
})

var userSchema = mongoose.model("user", schema);

http.createServer((req, res) => {
   userSchema.find().then((result, err) => {
       res.writeHead(200, { 'Content-Type': 'application/json' });
       res.end(JSON.stringify({status: 200, message: 'data retrive 
           successfully' data : result}));
  })
}).listen(port, () => {
   console.log(`your server are listing http://${hostname}:${port}`);
})

I hope it will help you, To create a server without using the express framework in nodeJS. 希望对您有所帮助,无需在nodeJS中使用express框架即可创建服务器。

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

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