gpt4 book ai didi

javascript - Mongoosejs .find 返回整个模型而不是文档

转载 作者:行者123 更新时间:2023-12-01 00:20:22 29 4
gpt4 key购买 nike

我正在现有模型上运行 .find() 查询。我过去使用过这段代码并且没有进行任何更改,但现在突然由于某种原因它不起作用。我认为 MongoDB 或 MongooseJS 已更新并且功能已更改。

var retrieve = function() {
Repo.find({}, function(err, docs) {
console.log(docs)
})
};

retrieve();

返回

[
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5e02e91c908f0f086e737189,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: [StateMachine],
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: [EventEmitter],
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
__v: 0,
stars: 2,
id: 1322,
url: 'url',
name: 'name',
_id: 5e02e91c908f0f086e737189
},
'$init': true
},
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5e02e92c3f6b72088246c563,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: [StateMachine],
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: [EventEmitter],
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
__v: 0,
stars: 2,
id: 2,
url: 'url1',
name: 'name1',
_id: 5e02e92c3f6b72088246c563
},
'$init': true
}
]

它应该返回

[{name: 'name', id: 2, url: 'url', stars: 2},
{name: 'name1', id: 1322, url: 'url1', stars: 2}]

我不知道为什么会这样

---- 为 Ahsok 编辑 ---我尝试使用你的代码

const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};

而且它仍然没有返回它需要的结果。现在它回来了

{
repo: [
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
},
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
}
]
}

这与上面返回的内容相同,只是格式略有不同

最佳答案

这是预期的行为, Mongoose 查找查询总是返回 Mongoose 的实例,即您所得到的。有两种方法可以处理这个问题:

  1. 自行将您的响应转换为普通对象:

console.log(docs.toObject())

  • 让 Mongoose 自己为你做这件事(使用lean):
  • Repo.find({}).lean().exec(function(err, docs) {
    console.log(docs);
    });

    您可以阅读有关精益的更多信息 here

    希望这有帮助:)

    关于javascript - Mongoosejs .find 返回整个模型而不是文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59475327/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com