【问题标题】:How to get data out of mongodb in actual webpage using node js, reactjs, express如何使用node js,reactjs,express从实际网页中的mongodb中获取数据
【发布时间】:2023-03-08 16:43:01
【问题描述】:

这是我在 mongo 终端上运行查询后得到的数据 db.contacts.find();

[ { _id: 59097d937386cc3a4e7b766b,
name: 'Oreo',
email: 'oreo@gmail.com',
education: 'B.tech',
address: 'West Bengal',
mobile_no: '9120507612',
__v: 0 },
{ _id: 5909814236b6663d8575fc1f,
 name: 'John',
 email: 'john@gmail.com',
 education: 'sports',
 address: 'New Delhi',
 mobile_no: '9234567788',
__v: 0 },
{ _id: 590982281eb9ab3dd5cf54b1,
name: 'Vicky',
email: 'vicky@gmail.com',
education: 'B.Tech',
address: 'Burgeon',
mobile_no: '123456789',
__v: 0 },

请推荐

【问题讨论】:

    标签: node.js mongodb reactjs express mongoose


    【解决方案1】:

    这可以通过使用猫鼬来完成。 Mongoose 是一个 MongoDB 对象建模工具,旨在在异步环境中工作。有关更多信息和示例,请参阅:https://www.npmjs.com/package/mongoose

    步骤:

    包括猫鼬:

    var mongoose = require('mongoose');
    

    连接数据库:

    mongoose.connect('mongodb://mongo:27017/yourdatabasename');
    

    定义架构:

    var contactSchema = mongoose.Schema({
    _id: String, //or _id: mongoose.Schema.Types.ObjectId
    name: String,
    email: String,
    education: String,
    adress: String,
    mobile_no: Number
    

    });

    定义模型:

    var ContactModel = mongoose.model('yourcollectionname', contactSchema); 
    

    随时提取数据并返回网页:

    app.get('/getusers', function(req, res) {
        ConcactMOdel.find({}}, function(err, foundData) { //empty query for all data
            if(err) {
                console.log(err);
                return res.status(500).send();
            } else {
                return res.status(200).send(foundData);
            }
        });
    });
    

    在您的网页上,您可以使用 AJAX 获取请求来获取您的数据,然后对其进行操作。

     var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (this.readyState == 4 && this.status == 200) 
        {
            var dataSet = JSON.parse(this.response);
            //manipulate/visualise the data as you wish
        }
    };
    xhttp.open("GET", "/getusers", true);
    xhttp.send();
    

    希望对你有帮助

    【讨论】:

    • 是的,真的很有帮助..谢谢..但仍然需要表格形式的 UI,并按行和按列排列。为此该怎么办。
    • @GeekDeveloper 检查有关如何调用数据的更新答案。对于表格可视化,SO 上已经有很多关于此的问题。
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2016-01-03
    • 1970-01-01
    • 2013-12-16
    • 2018-03-07
    • 2022-08-18
    相关资源
    最近更新 更多