我无法使用mongoose在mongoDB服务器中创建文档?

e4eetjau  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(83)

我无法在本地部署的mongodb服务器上使用mongoose正确创建文档。只有id正在创建不是完整的数据(名称,电子邮件,密码)我发送.在服务器中,数据看起来像这个{ "_id": { "$oid": "651d8f91c018db3d9504da2a" }, "__v": 0 } Mongosh shell,MongoDB compass工作正常。但mongosh shell给出了这样的警告:Access control is not enabled for the database..idk如果这是一个问题在这里或没有。
模式:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name : {type: String , 
        required: true 
    },
    email : {type: String ,
        required: true 
       },
    password : {type: String ,
         required: true 
        },
}, {timestamps: true});

module.exports = mongoose.model('user', userSchema);

超文本标记语言:

<div class="loginform">
      <div class="login">
        <label for="name">Name</label><input type="text" id="name" />
      </div>
      <div class="login">
        <label for="email">Email</label><input type="text" id="email" />
      </div>
      <div class="login">
        <label for="password">Password</label
        ><input type="text" id="password" />
        <button id="signinbutton">Create Account</button>
      </div>
    </div>

邮政请求前台

async function postData(url = "", data = {}) {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        });
        let rdata = await response.json()
        return rdata
      };

      let submit = document.getElementById("signinbutton")
      submit.addEventListener("click", async() => {
        let name = document.getElementById("name").value
        let email = document.getElementById("email").value
        let password = document.getElementById("password").value
        let resp= await  postData("/signin", { name, email, password })
        if(resp.success){
            alert("user created")
        }
       })

post请求

const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
var bodyParser = require('body-parser')
const postm = require('./models/post');
const User =  require('./models/User');
mongoose.connect('mongodb://127.0.0.1/blogbase');
app.use(express.json({extended:true}));
app.use(express.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, "static")));
 const port = 3000
 app.listen(port, () =>{
  console.log('app http://localhost:${port}')
});

 app.post('/signin', async(res,req) => {
  let user = await User.create(req.body)
  console.log(req.body)
  res.status(200).json({success: true, user: user })
});

误差

D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:3166
    this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: user validation failed: password: Path `password` is required., email: Path `email` is required., name: Path `name` is required.
    at Document.invalidate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:3166:32)
    at D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:2959:17
    at D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1368:9
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  errors: {
    password: ValidatorError: Path `password` is required.
        at validate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1365:13)
        at SchemaType.doValidate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1349:7)
        at D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:2951:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [Function (anonymous)],
        message: 'Path `password` is required.',
        type: 'required',
        path: 'password',
        value: undefined
      },
      kind: 'required',
      path: 'password',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    email: ValidatorError: Path `email` is required.
        at validate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1365:13)
        at SchemaType.doValidate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1349:7)
        at D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:2951:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [Function (anonymous)],
        message: 'Path `email` is required.',
        type: 'required',
        path: 'email',
        value: undefined
      },
      kind: 'required',
      path: 'email',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    name: ValidatorError: Path `name` is required.
        at validate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1365:13)
        at SchemaType.doValidate (D:\webdevedu\LBLOG\node_modules\mongoose\lib\schematype.js:1349:7)
        at D:\webdevedu\LBLOG\node_modules\mongoose\lib\document.js:2951:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [Function (anonymous)],
        message: 'Path `name` is required.',
        type: 'required',
        path: 'name',
        value: undefined
      },
      kind: 'required',
      path: 'name',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'user validation failed'
}

Node.js v18.17.0
[nodemon] app crashed - waiting for file changes before starting...
ukdjmx9f

ukdjmx9f1#

当mongoose模型尝试创建新用户时,emailnamepassword的值是未定义的。您的代码中有一些问题导致了这种情况,但看起来这些值没有被发送。
首先,如果您要提交表单数据,那么实际使用表单更符合语义。我可以看到您正在使用JS通过id获取元素,但<form>元素已经提供了一种访问每种输入类型的方便方法,因此只需给予每个输入一个name属性即可。我会解释的像这样更新你的HTML:

<form name="loginform" action="/signin">
   <div class="login">
      <label for="name">Name</label>
      <input type="text" id="name" name="name">
   </div>
   <div class="login">
      <label for="email">Email</label>
      <input type="text" id="email" name="email">
   </div>
   <div class="login">
      <label for="password">Password</label>
      <input type="text" id="password" name="password">
      <button id="signinbutton">Create Account</button>
   </div>
</form>

接下来,将addEventListener绑定到实际表单,并阻止其自动提交的默认行为。你也没有错误处理你的获取网络请求,所以你不知道你的表单是否正确发送。像这样更新:

const form = document.querySelector('form[name="loginform"]')
form.addEventListener('submit', (e)=>{
   e.preventDefault(); //< Prevent the form from submitting
   let name = form.elements.name.value; //< Get each input element
   let email = form.elements.email.value;
   let password = form.elements.password.value;
 
   fetch(form.action, { //< Now run fetch using form.action as url
      method: 'POST',
      body: JSON.stringify({ name, email, password }),
      headers: {
       'Content-type': 'application/json; charset=UTF-8',
      }
   })
   .then((response)=>{ 
      return response.json();
   })
   .then((data)=>{
      console.log(data);
      //Now handle a successful user creation 
   })
   .catch(error => {
      console.error('Error:', error)
      //Now handle an unsuccessful user creation 
   });
});

你的post路由在服务器上看起来没问题,但是你需要能够捕捉到任何错误。我建议像这样使用try/catch,并在错误时向客户端发送适当的响应:

app.post('/signin', async(req, res) => {
   console.log(req.body); //< Make sure the form data has been parsed in req.body
   try{
      const {name, email, password} = req.body; //< Destructure only the values you need
      let user = await User.create({name, email, password});
      res.status(200).json({success: true, user: user });
   }catch(err){
      console.log(err);
      res.status(400).json({success: false, err: 'Appropriate error message' });
   }
});

Access control is not enabled for the database是一个警告,而不是错误。它基本上是告诉你,你还没有设置用户身份验证。看看怎么做here
希望这对你的项目有帮助,祝你好运。

相关问题