【问题标题】:Mongoose find() returns undefined property and strange objectMongoose find() 返回未定义的属性和奇怪的对象
【发布时间】:2015-09-21 11:57:27
【问题描述】:

我有一个无法解决的错误,因为这是第一次发生在我身上。

这是我的查询:

    Pack.find(
            {idclient: clientId }
        )
        .populate({
            path: 'cards',
            options: { sort: { 'position': 1 } }
        })
        . exec(function(err,pack){
            if(err){
                console.log(err);
            }else{

                 ///
                // here are my logs

                callback(pack);
            }
        });

当我尝试使用 console.log(pack) 时,我可以看到带有 \n 的奇怪返回

{ __v: 1,\n  _id: 5596a859240cbd3832123b27,\n  grouped: 0,\n  idclient: \'4Z8OrisV2AMLZn_lAAAA\',\n  matId: 5596a859240cbd3832123b26,\n  reversed: 0,\n  roomId: 5596a859e37d7e7099cec1e6,\n  shuffled: 0,\n  type: \'hand\',\n  cards: [ 5596a859240cbd3832123b28, 5596a85c240cbd3832123b5d ],\n  date: Fri Jul 03 2015 17:20:57 GMT+0200 (CEST),\n  iscut: 0 }

通常,我可以看到一个格式很好的 Json 对象。

所以,当我尝试时:

console.log(pack.property) => 未定义 ...

有人遇到过这个问题吗?

谢谢

【问题讨论】:

  • Mongoose find 的回调返回一个数组...你试过 pack[0].property 吗?

标签: javascript node.js mongoose


【解决方案1】:

这个有两部分...

首先,Mongoose find 的回调返回一个数组... findOne 将返回一个对象。

就新行而言,mongoose 文档有一个用于 console.log 的 toString() 助手。它可能会添加换行符以提高可读性。在调用 console.log 之前将输出包装在 JSON.stringify(即 console.log(JSON.stringify(pack)))中,您将看到该文档为没有换行符的字符串。 -http://mongoosejs.com/docs/api.html#document_Document-toString

【讨论】:

    【解决方案2】:

    find() 返回一个数组,所以使用 findOne(),感谢 Adam Wysocki。

    有时我是愚蠢的开发者。

    【讨论】:

    • 不用担心,我们所有人都会遇到这种情况。我在下面编辑了我的答案以涵盖问题的两个部分。
    【解决方案3】:

    因为告诉 Model.find() 生成一个数组,所以这是我处理这种情况的方法:

    Kitten.find(function (err, kittens) {
        if (err) return console.error(err);
        kittens.forEach(function(kitten){
           console.log(kitten.name);
        }); 
    });
    

    在我看来,这是访问属性最清晰的方式

    【讨论】:

      猜你喜欢
      • 2018-05-18
      • 2019-08-16
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多