Mongoose 模型对象行为异常 [英] Mongoose Model Object behaves strangely

查看:25
本文介绍了Mongoose 模型对象行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mongoose 从数据库中获取人员数据.这是我使用的代码:

I am using mongoose to get person data from database. This is the code i use:

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)的输出

This is output from 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);

And this is result from console.log(result.firstname); and console.log(result.githubLink);

MyName
undefined

这个承诺是否以某种方式搞乱了这个结果?这真的很奇怪,因为只记录结果显示我的 github 链接,而记录链接显示未定义.

Is this promise somehow messing up with this result? It's really weird because logging only the result shows my github link and logging the link says undefined.

推荐答案

如果您的数据库对象中存在的字段实际上并不存在于为模型定义的架构中,那么它们仍然会记录"但您无法访问属性值正常.

If you have fields present in your database object that are not actually present in the Schema defined for the model, then they will still "log" but you cannot access the values of the property normally.

在大多数情况下,您确实希望在架构中正确定义项目:

In most cases you really want to define the item properly in your schema:

githubLink: String

或者您可以使用 访问您故意不想定义的属性.get() 方法:

Or you can access properties you deliberately do not want to define using the .get() method:

result.get('githubLink')

这篇关于Mongoose 模型对象行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆