use*_*710 3 javascript database mongoose mongodb node.js
我在现有模型上运行 .find() 查询。我过去曾使用过此代码并且什么也没改变,但现在突然由于某种原因它不起作用。我在想 MongoDB 或 MongooseJS 已更新并且功能已更改。
var retrieve = function() {
Repo.find({}, function(err, docs) {
console.log(docs)
})
};
retrieve();
Run Code Online (Sandbox Code Playgroud)
返回
[
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
}
]
Run Code Online (Sandbox Code Playgroud)
它应该返回
[{name: 'name', id: 2, url: 'url', stars: 2},
{name: 'name1', id: 1322, url: 'url1', stars: 2}]
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会这样
---- 为 Ahsok 编辑 --- 我尝试使用您的代码
const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};
Run Code Online (Sandbox Code Playgroud)
它仍然没有返回它需要的样子。现在它回来了
{
repo: [
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
},
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
}
]
}
Run Code Online (Sandbox Code Playgroud)
它与上面返回的内容相同,只是格式略有不同
这是预期的行为,Mongoose find 查询总是返回一个 mongoose 的实例,即你得到的。有两种方法可以处理这种情况:
console.log(docs.toObject())
Repo.find({}).lean().exec(function(err, docs) {
console.log(docs);
});
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关精益的更多信息
希望这可以帮助 :)
如果您使用异步函数,请使用此语法
const retrieve = async () => {
const repo = await Repo.find({})
console.log(repo)
};
Run Code Online (Sandbox Code Playgroud)
如果您不知道上面发生了什么,请使用此语法
const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};
Run Code Online (Sandbox Code Playgroud)
您也可以从这里乘坐和乘坐医生。
为什么会发生这种情况因为 find 返回游标或承诺从中检索 _doc 您需要使用承诺。这里,第一种解决方案很流行用于清理代码。
| 归档时间: |
|
| 查看次数: |
4012 次 |
| 最近记录: |