我正在现有模型上的.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
}
]
}
与上面返回的内容相同,只是格式略有不同
答案 0 :(得分:2)
这是预期的行为,Mongoose查找查询始终返回猫鼬的实例,即您得到的是什么。有两种处理方法:
console.log(docs.toObject())
Repo.find({}).lean().exec(function(err, docs) {
console.log(docs);
});
您可以了解有关精益here
的更多信息希望这会有所帮助:)
答案 1 :(得分:0)
如果您使用的是异步功能,请使用此语法
const retrieve = async () => {
const repo = await Repo.find({})
console.log(repo)
};
如果您不知道发生了什么,请使用此语法
const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};
您也可以从here进行文档骑乘。
为什么会发生这种情况,因为find返回游标或Promise从中检索_doc,所以您需要使用Promise。 在这里,第一种解决方案很流行清理代码。
答案 2 :(得分:0)
我知道了。原来,我必须将节点还原到以前的版本,这才是默认行为。正如Mohammed所指出的那样,使用.lean()也是可行的,但是我想知道为什么我的代码的行为方式与以前不同,结果却是由节点更新引起的。