猫鼬的findOne函数返回null/undefined [英] Mongoose findOne function returns null/undefined

查看:173
本文介绍了猫鼬的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 }));

这篇关于猫鼬的findOne函数返回null/undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆