javascript - 对 mongoose 返回的结果使用 lodash 时输出不正确

标签 javascript node.js mongodb express lodash

我有一个从 mongodb 查询返回的结果集,并且正在使用 lodash 重新格式化它。我正在尝试将对象数组转换为单个对象。问题是当我在结果集上使用 lodash 时,我得到了意外的输出。

注意:在 codepen/codesandbox 上运行代码片段会给出正确的输出,但直接从 mongoose 结果使用时则不会。

Mongoose 查询

try {
    const petInfo = await pets.find({ userId: user_id, petId: pet_id })
                              .select({
                                  "_id": 0,
                                  "createdAt": 0,
                                  "updatedAt": 0,
                                  "__v": 0
                              });

    if(!petInfo) {
        return res.status(400).json({ message: "FAILED_TO_FETCH_PET_INFO" });
    }

    let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
    return res.status(200).json(newObj);
}
catch (error) {
    req.errorMsg = error.message; // Log actual error
    return res.status(500).json({ message: "SOME_ERROR_OCCURRED" });
}

Mongoose 查找查询的结果 (petInfo)

[
    {
        "age": {
            "days": "",
            "months": "",
            "years": ""
        },
        "userId": "45422605180207851194",
        "name": "Oscar",
        "gender": "FEMALE",
        "type": "Dog",
        "breed": "",
        "weight": "",
        "spayOrNeuter": false,
        "petId": "KSVv7yJLnUWX3n"
    }
]

Lodash 代码片段

let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
return res.status(200).json(newObj);

修改后的结果

{
    "$__": {
        "strictMode": true,
        "selected": {
            "_id": 0,
            "createdAt": 0,
            "updatedAt": 0,
            "__v": 0
        },
        "getters": {
            "age": {
                "days": "",
                "months": "",
                "years": ""
            }
        },
        "wasPopulated": false,
        "scope": {
            "age": {
                "days": "",
                "months": "",
                "years": ""
            },
            "userId": "45422605180207851194",
            "name": "Oscar",
            "gender": "FEMALE",
            "type": "Dog",
            "breed": "",
            "weight": "",
            "spayOrNeuter": false,
            "petId": "KSVv7yJLnUWX3n"
        },
        "activePaths": {
            "paths": {
                "userId": "init",
                "petId": "init",
                "name": "init",
                "gender": "init",
                "type": "init",
                "breed": "init",
                "age.days": "init",
                "age.months": "init",
                "age.years": "init",
                "weight": "init",
                "spayOrNeuter": "init"
            },
            "states": {
                "ignore": {},
                "default": {},
                "init": {
                    "userId": true,
                    "name": true,
                    "gender": true,
                    "type": true,
                    "breed": true,
                    "age.days": true,
                    "age.months": true,
                    "age.years": true,
                    "weight": true,
                    "spayOrNeuter": true,
                    "petId": true
                },
                "modify": {},
                "require": {}
            },
            "stateNames": [
                "require",
                "modify",
                "init",
                "default",
                "ignore"
            ]
        },
        "pathsToScopes": {},
        "cachedRequired": {},
        "session": null,
        "$setCalled": {},
        "emitter": {
            "_events": {},
            "_eventsCount": 0,
            "_maxListeners": 0
        },
        "$options": {
            "skipId": true,
            "isNew": false,
            "willInit": true
        },
        "nestedPath": "age"
    },
    "isNew": false,
    "_doc": {
        "age": {
            "days": "",
            "months": "",
            "years": ""
        },
        "userId": "45422605180207851194",
        "name": "Oscar",
        "gender": "FEMALE",
        "type": "Dog",
        "breed": "",
        "weight": "",
        "spayOrNeuter": false,
        "petId": "KSVv7yJLnUWX3n"
    },
    "$locals": {},
    "$init": true
}

最佳答案

这样做的原因是因为 mongoose 不会返回您认为它会返回的对象。相反,它返回一个带有一堆方法等的“ Mongoose ”对象。有两种方法可以解决这个问题,或者调用 .lean()根据您的查询或 toJSON()在结果上将结果清理为普通的 js 对象。

.lean()

const petInfo = await pets.find({ userId: user_id, petId: pet_id })
    .select({
        "_id": 0,
        "createdAt": 0,
        "updatedAt": 0,
        "__v": 0
    }).lean();

.toJSON()

const petInfo = await pets.find({ userId: user_id, petId: pet_id })
    .select({
        "_id": 0,
        "createdAt": 0,
        "updatedAt": 0,
        "__v": 0
    }).lean();

const parsed = petInfo.toJSON()

关于javascript - 对 mongoose 返回的结果使用 lodash 时输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124332/

相关文章:

node.js - React 前端 MLab 访问的安全性

javascript - jQuery/Javascript - 使用附加的查询字符串重新加载当前页面?

javascript - 如何在 JavaScript 中使用 ISO-8859-15 字符集生成字符串?

Node.js Passport 在登录时未进行身份验证

node.js - socket.io 自动断开套接字

Node.js - 限制我发出的请求数量

mongodb - 如果在数组中找不到匹配项,则返回第一个元素

javascript - Angular 数据表添加 "tree view"

javascript - 无法让 jQuery 链接的 ajax 选择工作

javascript - "done() called multiple times" Mocha 月鹅