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
node 8.12.0
mongoose 5.4.0
body-parser 1.18.3
express 4.16.4
2 Answers
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
A cursory look at your code shows more than one syntax error
I don’t understand. What do you mean
The great God has answered