猫鼬的findOne函数返回null/undefined

问题描述:

在我的/authenticate路由中从数据库中获取数据时,我总是得到null/undefined.连接成功,并且用户存在于数据库中(已通过Robo 3T进行了检查).以下是代码摘录:

I always get null/undefined when fetching data from the database in my /authenticate route. Connection is successful and the user exists in the database (checked with Robo 3T). Here is an excerpt of the code:

var express = require("express");
var app = express();
var router = express.Router();
var mongoose = require("mongoose");
var user = require("../models/user");
var bodyParser = require("body-parser");
app.use(bodyParser.json());

router.post('/authenticate', function(req, res) {    
   user.findOne({ name: req.body.name }).then(function(foundUser) {
       if (!foundUser) { return res.status(404).send("No user matching name"); }
       return res.status(200).json(foundUser);
   });
});

这是我从邮递员处执行的请求:

Here is the request I'm executing from Postman:

修改后的答案:

要让Express解析除json之外的表单数据,您需要在应用程序中添加第二个正文解析器:

For express to parse form data in addition to json you need to add a second body parser to your application:

var app = require('express');
var bodyParser = require('body-parser');

// Enable express to parse body data from raw application/json data
app.use(bodyParser.json());

// Enables express to parse body data from x-www-form-encoded data
app.use(bodyParser.urlencoded({ extended: false }));