findOne函数在此代码中不起作用

时间:2019-04-23 23:57:36

标签: api authentication

我遇到findOne dosnt工作的问题,我不确定自己做错了什么:

import express from 'express'
import path from 'path'
import mongoose from "mongoose"
import bodyParser from "body-parser";
import auth from "./auth";






const app=express()


app.use(bodyParser.json())

mongoose.connect('mongodb://localhost/shoppinglist',{useMongoClient:true})


app.use("/api/auth",auth)


import express from "express";
import User from './User'


const router = express.Router();


router.post("/",function(req, res) {




        User.findOne({username: req.body.credentials.username},(user)=>{
            if (!user) {
                  res.status(400).json({ errors: { global: "really???!!!" } });
            }})




  });
  export default router;
import mongoose from "mongoose";

const schema = new mongoose.Schema(
{
   username:String,

}   

  );

  module.exports = mongoose.model("User", schema);
有什么建议吗?代码选择了req.body.username,但是findOne不会检查用户。我猜我在User.js文件上犯了一些错误

1 个答案:

答案 0 :(得分:0)

回调参数不正确。回调接受两个参数:err和document。如果您遇到参数err丢失的情况,请尝试此操作。

User.findOne({username: req.body.credentials.username}, (err, user) => {
  if (!user) {
    return res.status(400).json({ errors: { global: "really???!!!" } });
  } 
  return res.status(200).json({data: user});
});