node.js - 如果这个nodejs Rest api 正常并且它的 mongoose 结构和 mongodb 数据正常的话,为什么我会从 mongoDB 得到空值?

标签 node.js mongodb express mongoose

此 API 获取一个请求参数,该参数被过滤并传递给 User mongoose 模型,如下面的代码所示,正在查询 mongodb 并返回空。如果一切正常,为什么会发生这种情况?

routes.route('/user')
    .get( (req,res) => {
        //const query = req.query;
        //const {query} = req;
        const {query} = req;
        
        if (req.query.UserName){
            query.UserName = req.query.UserName;
            console.log("ok 2 " + query.UserName);
        }      

        User.find({UserName:query.UserName}, (err, data)=> {
            if (err){
                console.log("not ok");
                return res.send(err);
            }
            else {
                console.log("ok: " + data);                
                return res.json(data);
            }
            
        });
    });

为了测试我的 API,我使用 postman 或 webbrowser 使用以下 URL: http://localhost:4000/api/user?UserName=smed

查看日志时,可以看到它打印了参数和空值数据。

这是 Mongoose 模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let UserSchema = new Schema({
    UserId: {
        type: Number
    },
    PersonId: {
        type: Number
    },
    UserName: {
        type: String,
        unique: true
    },
    Deactivated: {
        type: Boolean
    },
    Password: {
        type: String
    },
    SysCreationDate: {
        type: Date
    },
    LastLoginDate: {
        type: Date
    }

},{collection:'User'});

module.exports = mongoose.model('User', UserSchema);

以及mongo中的数据:

{"_id":{"$oid":"5d1037acde2b6feb37938db6"},"User":[{"UserId":
{"$numberInt":"1"},"PersonId":{"$numberInt":"1"},"UserName":"smed","Deactivated":false,"Password":"1234","SysCreationDate":"2016-06-23T21:42:31+07:00"},{"UserId":{"$numberInt":"2"},"PersonId":{"$numberInt":"2"},"UserName":"eper","Deactivated":false,"Password":"1234","SysCreationDate":"2016-06-23T22:42:31+07:00"}]}

我已经在 Windows 10 和 Ubuntu 18.x.x 机器上对此进行了测试,并且出现了相同的错误。 这些是我的依赖项:

"dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.6.2"
  }

和 NodeJS:v8.10.0

响应是 json 中的空数组。它应该查询 User 集合并返回 UserName 属性为“smed”时包含的对象,即请求中发送的参数: http://localhost:4000/api/user?UserName=smed

当 UserName=smed 时,它应该返回 mongo 数据(如前所示)

{"_id":{"$oid":"5d1037acde2b6feb37938db6"},"User":[{"UserId":{"$numberInt":"1"},"PersonId":{"$numberInt":"1"},"UserName":"smed","Deactivated":false,"Password":"1234","SysCreationDate":"2016-06-23T21:42:31+07:00"}]}

最佳答案

似乎您执行了错误的查询,请尝试使用以下代码:

routes.route('/user').get((req, res) => {
    const query = (req.query.userName) ? {
        User: {
            $elemMatch: {
                $eq: req.query.userName
            }
        }
    } : {};
    User.find(query, (err, data) => {
        if (err) {
            console.log("Error is: ", err);
            return res.send(err);
        } else {
            console.log("Data is: " + data);
            return res.json(data);
        }

    });
});

或者使用 es6 async/await:

routes.route('/user').get(async (req, res) => {
    try {
        const query = (req.query.userName) ? {
            User: {
                $elemMatch: {
                    $eq: req.query.userName
                }
            }
        } : {};
        const data = await User.find(query).lean();
        console.log("Data is: " + data);
        return res.json(data);
    } catch (err) {
        console.log("Error is: ", err);
        return res.send(err);
    }
});

希望这有帮助:)

关于node.js - 如果这个nodejs Rest api 正常并且它的 mongoose 结构和 mongodb 数据正常的话,为什么我会从 mongoDB 得到空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56858623/

相关文章:

node.js - React 16 不适用于 enzyme

node.js - fs.renameSync() 抛出错误 : ENOTDIR, 不是目录,但目录存在

javascript - Express 中间件、next 和 Promises

javascript - 如何使用键值对获取数组的lastindex

javascript - 如何在 Windows 7 中使用 Nodejs?

mongodb - Casbah Mongo 作为 scala 数组 : is this the most elegant way?

javascript - document.cookie : Works in localhost but Returns Empty on Web Hosting 问题

node.js - 如何对 express-http-proxy 进行单元测试

python - 在 MongoDB 中的一个查询中更新字段和 $push 到数组

python - mongoDB 和流数据 - 如何获取最新结果?