Express is using Model to operate mongodb Times wrong, I don't know why, ask for advice

when you create a user, you will first query the data in the table. There is a mistake here in the query. I don"t understand the reason. Please give me some advice:

user model: models/User.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    userName:{
        type:String,
        required:true
    },
    userEmail:{
        type:String,
        required:true
    },
    userPassword:{
        type:String,
        required:true
    },
    userAvatar:{
        type:String
    },
    userDate:{
        type:Date,
        default:Date.now
    }
 });

const UserModel = mongoose.model("User",UserSchema);
module.exports = UserModel; 

define routes and query table router/api/user.js:

 const express = require("express");
 const router = express.Router();
 const myModel = require("../../models/User");

  /**
  * POST api/user/register
  */
 router.post("/register",(req,res) => {
     //
    var users = new myModel (req.body);
    //
    users.findOne({userName:req.body.userName})
        .then((user) => {
            if(user){
                return res.status(400).json({userName:""})
            }else{
                const newUser = newUser({
                    userName: req.body.userName,
                    userEmail:req.body.userEmail,
                    userPassword: req.body.userPassword,
                    userAvatar:req.body.userAvatar,
                    userDate:req.body.userDate
                })
            }
        });
    //
        
    //
    user.save()
        .then(user => res.json(user))
        .catch(err => console.log(err));
 })

 module.exports = router;

prompt the following message when using the postman test:
http://localhost:5000/api/user/register?userId=302&userName=kevin.chen&userEmail=kevin.chen@anviz.com&userPassword=123456

clipboard.png

node 8.12.0
mongoose 5.4.0
body-parser 1.18.3
express 4.16.4

Feb.24,2022

Brother
clipboard.png
I took a cursory look at your code. There is more than one syntax error


change users.findOne to myModel.findOne

.
Menu