繁体   English   中英

无法存储从 node.js 到 mongoDB 图集的数据 下面是代码片段

[英]Unable to store the data from node.js to mongoDB atlas below are the code snippets

我无法存储从 node.js 到 mongoDB 的数据图集下面是代码片段。

下面是我建立 mongodb 连接的 app.js 代码。

const express = require("express");
var app = express();
const bodyparser = require("body-parser");
const cors = require("cors");
const Post=require("./models/post");
const mongoose=require("mongoose");
app.use(bodyparser.urlencoded({ extended: false }))
app.use(bodyparser.json())
app.use(cors());
app.post('/sms', function (req, res) {
  let obj=JSON.parse(req.body.user);
   const user= new Post({
     userName:obj.userName,
     password:obj.password,
     email:obj.email,
     address:obj.address
   })
  user.save()
  .then(data => {
    res.json(data),
    res.status(200).json({data})
  })
  .catch(err => {
    res.json(err)
  });
})
mongoose.connect("mongodb+srv://srihari:srihari@cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
  console.log("DB connected!");
})
app.listen(8080); 

下面是用于绑定来自前端的数据的 Schema 代码。

const mongoose = require("mongoose");
const postschema=mongoose.Schema({
    userName:{
        type:String 
    },
    password:{
        type:String
    },
    email:{
        type:String 
    },  
    address:{
        type:String 
    },

});
module.exports = mongoose.model('Posts',postschema)

在 mongodb 中存储/检索数据时尝试使用 Async/Await 函数;

   const express = require("express");
   var app = express();
   const bodyparser = require("body-parser");
   const cors = require("cors");
   const Post=require("./models/post");
   const mongoose=require("mongoose");
   app.use(bodyparser.urlencoded({ extended: false }))
   app.use(bodyparser.json())
   app.use(cors());
   app.post('/sms', async function (req, res) {
     let obj=JSON.parse(req.body.user);
      const user= new Post({
         userName:obj.userName,
         password:obj.password,
         email:obj.email,
         address:obj.address
      })
      await user.save()
      .then(data => {
         res.json(data),
         res.status(200).json({data})
       })
       .catch(err => {
          res.json(err)
       });
    })
     mongoose.connect("mongodb+srv://srihari:srihari@cluster0-yuykq.mongodb.net/srihari?retryWrites=true&w=majority",{useNewUrlParser:true,useUnifiedTopology:true},()=>{
     console.log("DB connected!");
      })
     app.listen(8080);

这是因为您直接使用 Schema。 首先,您必须像下面这样定义它。

常量架构 = mongoose.Schema;

导入 mongoose 后编写上面的代码行。

暂无
暂无

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

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