const express = require("express")
const app = express()
const cors = require("cors")
const mongoose = require("mongoose")
const User = "./models/user.model"
app.use(cors())
app.use(express.json())
mongoose.connect("mongodb://localhost:27017/full-mern-stack")
app.get("/",(req,res)=>{
res.send("home page")
})
app.get("/api/register",(req,res)=>{
res.send("Correct Route")
})
app.post("/api/register", async (req,res)=> {
try{
await User.create({
name:req.body.name,
email:req.body.email,
password:req.body.password,
})
res.json({status:"ok"})
}catch(err){
console.log(err)
res.json({status:"error",error:"Duplicate email"})
}
})
app.post("/api/login", async (req,res)=> {
const user = await User.findOne({
email:req.body.email,
password:req.body.password,
})
if (user) {
return res.json({status:"ok",user:true})
} else{
return res.json({status:"error",user:false})
}
res.json({status:"ok"})
})
app.listen(3002,()=>{
console.log("listening")
})
im getting this error :TypeError: User.create is not a function at C:\Users\joshm\Downloads\New folder (12)\myapp\Server\Server.js:18:16 at Layer.handle [as handle_request] (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\layer.js:95:5) at C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\index.js:341:12) at next (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\express\lib\router\index.js:275:10) at C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\body-parser\lib\read.js:130:5 at invokeCallback (C:\Users\joshm\Downloads\New folder (12)\myapp\node_modules\raw-body\index.js:224:16)
model :
const mongoose = require("mongoose")
const User = new mongoose.Schema({
name:{type:String,required:true},
email:{type:String,required:true,unique:true},
name:{type:String,required:true},
quote:{type:String},
},
{collection:"user-data"}
)
const model = mongoose.model("UserData",User)
module.exports = model
3条答案
按热度按时间ijxebb2r1#
您以错误的方式要求模型,请将
const User = "./models/user.model"
更改为const User = require("./models/model")
您在模型文件中导出的内容。
x33g5p2x2#
您可以通过以下方式更改User.js,
然后在index.js文件中这样导入
e0bqpujr3#
用户模型
美国石油学会
如果上述路由创建功能不起作用,则使用此功能
在这里,我们创建一个示例,然后保存在数据库中。