DWQA QuestionsCategory: DatabaseExpress reported an error while using model to operate mongodb. I don't know why. Please give me some advice
baiyygynui888 asked 2 months ago

When you create a user, you will query the data in the table first. There is an error in the query, and you don’t understand the reason. Please point out:
User models: 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 route 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) => {
     //Create objects from the user model
    var users = new myModel (req.body);
    //Query database
    users.findOne({userName:req.body.userName})
        .then((user) => {
            if(user){
                return  res.status (400). JSON ({Username: 'user name already exists'})
            }else{
                const newUser = newUser({
                    userName: req.body.userName,
                    userEmail:req.body.userEmail,
                    userPassword: req.body.userPassword,
                    userAvatar:req.body.userAvatar,
                    userDate:req.body.userDate
                })
            }
        });
    //Encrypt the data and save it to the database
        
    //Save data to database
    user.save()
        .then(user => res.json(user))
        .catch(err => console.log(err));
 })

 module.exports = router;

When using postman test, the following information is prompted:
http://localhost:5000/api/user/register?userId=302&userName=kevin.chen&[email protected]&userPassword=123456
clipboard.png
node 8.12.0
mongoose 5.4.0
body-parser 1.18.3
express 4.16.4

myth replied 2 months ago

The great God has answered

2 Answers
Green jade answered 2 months ago

Brother, it’s not that you can’t find the data because you can’t save it successfully. The syntax of findone not a function is wrong
clipboard.png
A cursory look at your code shows more than one syntax error

baiyygynui888 replied 2 months ago

I don’t understand. What do you mean

XYShaoKang answered 2 months ago

holdusers.findOneChange tomyModel.findOne