Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...