无法从猫鼬对象获取属性 [英] Impossible to get property from mongoose object

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

问题描述

我对猫鼬有一种奇怪的行为.当我 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

或者,要访问它,即使它未在您的架构中定义,请使用 get 方法:

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天全站免登陆