我正在使用 Mongoose 从数据库中获取人员数据。这是我使用的代码:
return new Promise((resolve, reject) => {
Person.findOne({}, (err, result) => {
if(err) {
reject(err);
} else {
console.log(result);
console.log(result.firstname);
console.log(result.githubLink);
resolve(result);
}
});
});
这是 console.log(result) 的输出
{ _id: 593c35e6ed9581db3ef85d75,
firstname: 'MyName',
lastname: 'MyLastName',
jobtitle: 'Web Developer',
email: 'foo@example.com',
githubLink: 'https://github.com/myGithub' }
这是 console.log(result.firstname); 的结果。和 console.log(result.githubLink);
MyName
undefined
这个 promise 是否会以某种方式扰乱这个结果?这真的很奇怪,因为只记录结果显示我的 github 链接,而记录链接则显示未定义。
最佳答案
如果数据库对象中存在的字段实际上并不存在于为模型定义的架构中,那么它们仍然会“记录”,但您无法正常访问属性的值。
在大多数情况下,您确实希望在架构中正确定义项目:
githubLink: String
或者您可以使用.get()
访问您故意不想定义的属性。方法:
result.get('githubLink')
关于javascript - Mongoose 模型对象行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44482425/