mongoose 和 node.js 中的验证错误(错误如下)

Posted

技术标签:

【中文标题】mongoose 和 node.js 中的验证错误(错误如下)【英文标题】:Validation Error in mongoose and node.js (ERROR IS BELOW) 【发布时间】:2022-01-01 23:33:12 【问题描述】:

我收到了这个错误

this.$__.validationError = new ValidationError(this);

完整的错误信息将在代码下方

index.js 文件

//Requiring Dependencies
const express = require('express');
const app = express();

const mongoose = require('mongoose');

const path = require('path');

const session = require('express-session');

const passport = require('passport');
const LocalStrategy = require('passport-local')

//Require Models
const Product = require('./models/product');
const User = require('./models/user');

//To run and parse EJS
const engine = require('ejs-mate');

//Connecting to DB server
mongoose.connect('mongodb://localhost:27017/ecom', 
    useNewUrlParser: true,
    useUnifiedTopology: true,
)
    .then(() => 
        console.log('DATABASE CONNECTED')
    )
    .catch(err => 
        console.log('SOMETHING WENT WRONG WITH MONGO')
        console.log(err)
    )

    //Using EJS-Mate
    app.engine('ejs' , engine);
    app.set('view engine' , 'ejs');
    app.set('views' , path.join(__dirname, 'views'));

    const sessionConfig = 
        secret: 'secrethere',
        resave: false,
        saveUninitialized: true,
        cookie: 
            httpOnly: true,
            expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
            maxAge: 1000 * 60 * 60 * 24 * 7
        
    
    app.use(session(sessionConfig))

    //Using Passport
    app.use(passport.initialize())
    //So user does not have to login after every single request
    app.use(passport.session())
    passport.use(new LocalStrategy(User.authenticate()))

    
    //How to store a user in the session
    passport.serializeUser(User.serializeUser());

    //How to get user out of that session
    passport.deserializeUser(User.deserializeUser());


    app.use(express.urlencoded(extended: true));

    //For use of files like js and css in public directory
    app.use(express.static(path.join(__dirname, './public')))

    app.use(express.static(path.join(__dirname, './images')))

   


    app.get('/' , (req , res) => 

    )

    app.get('/home' , (req , res) => 
        res.render('pages/homepage')
    )

    app.get('/login' , (req , res) => 
        res.render('pages/loginPage')
    )

    app.get('/signup' ,(req , res) => 
        res.render('pages/signup')
    )

    //Creating a new user
    app.post('/signup' , async(req , res) => 
        const username , email, password, country, city, zipcode, street = req.body
        const user =  new User(
            username,
            email,
            country,
            city,
            zipcode,
            street
        )
      const registeredUser = await User.register(user, password);
      console.log(registeredUser)
    )


    //Port
app.listen(3000, () => 
    console.log('LISTENING ON PORT 3000')
)

这是用户模型文件

const express = require('express')
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new Schema(
    email: 
        type: String,
        required: true,
        unique: true
    ,
    username: 
        type: String,
        required: true
    ,
    address: 
        country: 
            type: String,
            required: true
        ,
        city:
            type: String,
            required: true
        ,
        street: 
            type: String,
            required: true
        ,
        zipcode: 
            type: String,
            required: true
        
    ,
    shipping_address: 
        country: 
            type: String,
            required: true
        ,
        street: 
            type: String,
            required: true
        ,
        zipcode: 
            type: String,
            required: true
        
    
);
//Using Paspport Plugin
userSchema.plugin(passportLocalMongoose);

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

这是完整的错误

C:\Users\hadiz\Desktop\Business\portfolioprojects\ecommerce\node_modules\mongoose\lib\document.js:2907 this.$__.validationError = new ValidationError(this); ^

ValidationError:用户验证失败:shipping_address.zipcode: 路径shipping_address.zipcode 为必填项,shipping_address.street: 路径shipping_address.street 为必填项,shipping_address.country: 路径shipping_address.country为必填项,地址.邮编:路径 address.zipcode 为必填项,地址.street: 路径address.street 是必需的。,address.city:路径address.city是必需的。, address.country:路径address.country 是必需的。 在model.Document.invalidate

【问题讨论】:

【参考方案1】:

在注册新用户时,您应该参考架构中 addressshipping_address 对象的嵌套属性:

app.post('/signup', async (req, res) => 
  const  username, email, password, country, city, zipcode, street  =
    req.body;
  const user = new User(
    username,
    email,
    address:  country, city, zipcode, street ,
    shipping_address:  country, city, zipcode ,
  );
  const registeredUser = await User.register(user, password);
  console.log(registeredUser);
);

【讨论】:

【参考方案2】:

这是因为送货地址是架构中的嵌套对象,是必需的。

改成

const user=newUser(

username,email,

shipping_address:zipcode,street,country,

address:city,zipcode,street,country

)

【讨论】:

以上是关于mongoose 和 node.js 中的验证错误(错误如下)的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Mongoose/Mongodb 与 node.js- 护照身份验证一起使用

如何使用 Node.js、Express 和 Mongoose 进行身份验证?

Node.js/Mongoose 上的“版本错误:未找到匹配的文档”错误

本地护照和本地护照猫鼬的身份验证错误

Node.js 和 MongoDB Atlas Mongoose 连接错误

mongoose .create 给 node.js “ValidationError:验证失败:转换为 [undefined] 值失败......”