不可能从猫鼬对象获得财产 [英] Impossible to get property from mongoose object

查看:61
本文介绍了不可能从猫鼬对象获得财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和猫鼬在一起的行为很奇怪.当我console.log结果对象时,我看到该属性在这里,但是当我尝试仅获取所需的值(例如console.log(obj.propt))时,它返回未定义.

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

奇怪的是,如果我使用.toObject方法,它可以工作.我肯定错过了什么.有人对此有解释吗?

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

推荐答案

当MongoDB文档中存在一个字段但您的Mongoose模式中未定义字段时,就会发生这种情况.

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

因此请确保在您的ServerModel模式中将其定义为

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

这篇关于不可能从猫鼬对象获得财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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