【问题标题】:Get key from the document object in mongodb using node使用节点从 mongodb 中的文档对象中获取密钥
【发布时间】:2018-02-27 10:34:04
【问题描述】:

我是 node 和 mongodb 的初学者。我正在尝试从使用 mongoose 的查询返回的对象中记录一个值。如果我在循环中运行它,我可以获得该值,但我试图在不使用循环的情况下获取该值。

这是我的代码

That.find({$and: [{"userId" : {"$ne" : ""}},{"userId" : {"$exists" : true}}]}).sort({"_id" : -1}).limit(1).select("userId").exec(function(err, doc)
            {
                if(err)
                {
                    console.log('User ID ERROR-');
                    callback({error:err,message:"Error getting max user ID"});
                }else {
                    console.log('User ID-');
                    console.log(doc);
                    console.log(typeof(doc));
                    doc.forEach(function(eachdoc) {
                        console.log(eachdoc.userId);
                    });
                    process.exit();
                }
            });

而不是做

doc.forEach(function(eachdoc) {
    console.log(eachdoc.userId);
});

如果我是console.log(doc.userId);,为什么是undefined

还有什么办法可以从结果中去掉_id

非常感谢任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在 find 函数中的查询对象之后添加 {_id :0} 以从 result. doc 中删除 _id 是一个您无法直接访问值的数组,您必须使用循环或 doc[0].userId .

    That.find({
        $and: [{
            "userId": {
                "$ne": ""
            }
        }, {
            "userId": {
                "$exists": true
            }
        }]
    }, {
        _id: 0
    }).sort({
        "_id": -1
    }).limit(1).select("userId")
    

    【讨论】:

      【解决方案2】:

      回答第一个问题,可以使用

      console.log(doc[0].userId); 
      

      而不是

      doc.forEach(function(eachdoc) {
          console.log(eachdoc.userId);
      });
      

      第二个问题请参考How to prevent MongoDB from returning the object ID when finding a document?

      【讨论】:

      • 感谢您的帮助。
      猜你喜欢
      • 2021-09-25
      • 2019-10-10
      • 2013-09-16
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多