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
513 views
in Technique[技术] by (71.8m points)

node.js - Impossible to get property from mongoose object

I'm having a strange behaviour with mongoose. When I console.log the result object, I see that the property is here, but when I try to get just the desired value like console.log(obj.propt)it return undefined.

ServerModel.findOne(function (err, server) {
    if (err) {
        return console.error(err);
    }

    console.log(server);
    // output:
    // {_id: 55ead0eb4105b7df958256af,
    // name: 'st1',
    // ip: '57.29.42.241',
    // capacity: 0,
    // totalUsed: 0,
    // state: true }

    console.log(server.ip);
    // output: undefined

    console.log(server.name);
    // output: st1

    // but that works if I use the toObject method
    var srvr = server.toObject();

    var serverAddress = srvr.ip;
    // serverAddress is 57.29.42.241
});

Strangely, it works if I use the .toObject method. I must have missed something. Does anyone has an explanation for that?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This will happen when a field is present in the MongoDB document, but not defined in your Mongoose schema.

So be sure to define it in your ServerModel schema as

ip: String

Or, to access it even though it's not defined in your schema, use the get method:

console.log(server.get('ip'));

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

...