Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - Mongoose Model Object behaves strangely

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);
      }
    });
  });

This is output from console.log(result)

{ _id: 593c35e6ed9581db3ef85d75,
firstname: 'MyName',
lastname: 'MyLastName',
jobtitle: 'Web Developer',
email: '[email protected]',
githubLink: 'https://github.com/myGithub' }

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

MyName
undefined

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

result.get('githubLink')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...