本文介绍了Mongoose .find 查询结果包含查询元数据?不能只是手动投影集合的每个属性,如何只获取文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档数组 看起来像这样 一旦从后端检索:

My array of docs looks like this once retreived from the backend:

41:
$__: {strictMode: true, selected: {…}, shardval: null, saveError: null, validationError: {…}, …}
$init: true
$locals: {}
errors: {undefined: {…}, files: {…}}
isNew: false
_doc: {status: "Finished", isOnHold: false, requirements: Array(0), files: Array(0), reportFileIds: Array(1), …}
__proto__: Object

每个项目的实际文档都在 _doc 下.这是 mongoose.Find 查询的结果:

The actual doc being under _doc for each item. This is the result of a mongoose.Find query:

        let query = Job.find({
            _id: {
                $in: data.jobs
            }
        });

        let result = await query.exec();

现在,如果我在发送之前尝试获取该结果数组的项目,它看起来不像在前端实际建模的东西,这很奇怪.

Now if I try to get items of that result array before I send it, it doesn't look like what's actually modelled on the frontend which is weird.

有什么方法可以使用 mongoose.find 获取纯文档数组?我不能使用聚合查询,因为我不想手动投影每个可能的属性.

Is there any way to get just the pure array of documents using mongoose.find? I cannot use aggregate queries as I don't want to manually project each possible property.

这不是大声喊出来的重复,传播语法与它无关,你看到我在任何地方提到传播语法吗?这个跟mongoose驱动有关.

This is not a duplicate for crying out loud, spread syntax has nothing to do with it, do you see me mentioning the spread syntax anywhere? This is related to the mongoose driver.

Edit2:我最终循环遍历数组并在每个项目上调用 .toObject:

I ended up looping over the array and calling .toObject on each item:

        let jobs = await query.exec();
        let result = [];
        for (let doc of jobs) {
            result.push(doc.toObject());
        }
        return result;

Edit3:最终调用 query.lean().exec() 做了正确的事情.我过去基于可能已经过时的 stackoverflow 示例使用精益部分作为参数,它只会返回文档的 ID.但是像上面那样调用它可以正常工作.

Ended up calling query.lean().exec() which did the right thing. I used the lean part as a parameter in the past based on a stackoverflow example that's probably outdated and it would only return the ID's of the documents. But calling it like above works fine.

推荐答案

Mongoose 总是返回一个实例 mongoose 对象,默认情况下是不可变的.要获取纯 JS 对象,请尝试使用 lean() 进行查询,如下所示:

Mongoose always return an instance mongoose object, which is immutable by default. To get the plain JS object, try query with lean() like this:

const query = Job.find({
    _id: {
        $in: data.jobs
    }
});

let result = await query.lean().exec();

您可以在以下位置阅读有关精益的更多信息:https://mongoosejs.com/docs/tutorials/lean.html

You can read more on lean at: https://mongoosejs.com/docs/tutorials/lean.html

希望这有帮助:)

这篇关于Mongoose .find 查询结果包含查询元数据?不能只是手动投影集合的每个属性,如何只获取文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:54