Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

javascript - 当对猫鼬返回的结果使用lodash时输出不正确(Incorrect output when using lodash on results returned by mongoose)

I have a result set returned from a mongodb query and am using lodash to reformat it.

(我有一个从mongodb查询返回的结果集,并且正在使用lodash重新格式化它。)

I am trying to convert the array of objects into a single object.

(我正在尝试将对象数组转换为单个对象。)

The problem is when I use lodash on the result set, I get unexpected output.

(问题是当我在结果集上使用lodash时,得到了意外的输出。)

NOTE: Running the snippet on codepen/codesandbox gives correct output, but not when used directly from mongoose results.

(注意:在codepen / codesandbox上运行代码片段将提供正确的输出,但不能直接用于猫鼬结果中。)

Mongoose Query

(猫鼬查询)

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" });
}

Result from mongoose find query (petInfo)

(猫鼬查找查询(petInfo)的结果)

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

Lodash snippet

(Lodash片段)

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

Result after modification

(修改后的结果)

{
    "$__": {
        "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
}
  ask by Ayan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason for this is because mongoose doesn't return the object you think it does.

(其原因是因为猫鼬不会返回您认为会返回的对象。)

Instead, it returns a 'mongoose' object with a bunch of methods ect ect.

(而是返回带有一系列方法的“猫鼬”对象。)

There are 2 ways around this, either call .lean() on your query or toJSON() on the result to sanitize result into normal js object.

(有两种解决方法,要么在查询中调用.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()

(.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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...