首页 > 解决方案 > 如何将 mongodb 数据库的内容显示到前端?

问题描述

基本上我需要从我的 html 中检索用户输入。使用该输入通过 mongoose 搜索我的 mongoDB 数据库。然后检索该信息并将其显示到前端。我不知道该怎么做。

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


检索数据意味着向您的节点端点发送获取请求

由于我使用 axios,我会建议您也使用 axios(如果您使用的是 react 或任何其他框架,请 npm install axios)或者您可以简单地复制它的脚本 CDN

从前端你可以简单地

axios.get("Your url address" + "api route address").then((response) => {
         //do whatever with your response
        }).catch(error => {
         //Do something in case of error 
       })

取一个实际地址,假设我有一个节点服务器连接到在 localhost 上运行的 mongoose 8000,我的 api 端点看起来像这样(后端

我在哪里像这样导入了我的用户模式

const User = require("./../models/userSchema.js")
const User = require("./../models/userSchema.js")

router.get("/",  async (req, res) => {
  const contactList  = await User.find({}) //coming from mongoose 
  res.send(contactList)
})

通过 axios,我的 api 请求是这样的(前端

axios.get("http://localhost:8000/").then((response) => {

后端部分 -> 发布请求

首先像这样定义和导出一个猫鼬模式

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    address: String, 
    email: {
        type: String,
        default: "www.xyz@abc.com"
    },
    number: Number,
    OTP: Number,
    createdAt: {type: Date, default: Date.now},
    DateOfBirth: {
        type: String,
        default: "1/01/2001"
    },
    image: {
        type: String,
        default: "http://icons.iconarchive.com/icons/graphicloads/100-flat/256/contact-icon.png"
    }, 

})


module.exports = mongoose.model("User", userSchema)

然后,希望您已使用 MVC 模式配置节点,将其导入需要使用模式的路由

const express = require("express")
const router = express.Router() 
const User = require("./../models/userSchema.js")

在该模式中创建一个接受发布请求(或放置请求)的 API 路由或端点

  router.post("/message", async (req, res) => {
  const newMessage = new User({
     firstName: req.body.(whatever from your request contains firstName
    .....
    ......
    )}
  })

一旦你填写了你得到req.body的数据(包含数据)你需要保存它,在上面的路线上扩展

 router.post("/message", async (req, res) => {
  const newMessage = new User({
     firstName: req.body.(whatever from your request contains firstName
    .....
    ......
    )}
newMessage.save().then((response) => {
if (error) {
      console.log(error)
      throw  new Error (error)
      } else {
        console.dir(responseData)
        res.send(responseData)
      }
  })
  })

前端部分

由于我使用 axios,我会建议您也使用 axios(如果您使用的是 react 或任何其他框架,请 npm install axios)或者您可以简单地复制它的脚本 CDN

在 axios 内部,我们发送 post 请求

 axios.post("Your port address" + Message , object).then(response => {   
          console.log(response)
          }).catch(error => {
            console.log(error)  
          })

推荐阅读