【问题标题】:How to return only value of a field in mongodb using node js.如何使用节点 js 仅返回 mongodb 中字段的值。
【发布时间】:2018-07-27 01:18:48
【问题描述】:

当我用这种方法查询我的mongodb数据库时:

app.get('/', function (req, res) {

    user.find({}, {twitter: 0, _id: 0, __v:0,}, function (err, result) {
        if (err) throw err; 

        console.log(result); 

        res.render('pages/index', {

            path: result


        });
    });

});

我得到了这个结果作为回报:

{ meme: { imgs: 'http://localhost/public/Images/okro.jpg' } }
{ meme: { imgs: 'http://localhost/public/Images/1518530337363-okro.jpg' } }
{ meme: { imgs: 'http://localhost/public/Images/1518530481130-meme.jpg' } } 

但我希望它返回 imgs 字段中的实际值。

我想要这样的东西。

 {'http://localhost/public/Images/okro.jpg'} 
{'http://localhost/public/Images/1518530337363-okro.jpg'} 
{ 'http://localhost/public/Images/1518530481130-meme.jpg' }

这在 MongoDB 中如何使用 node js 实现?

【问题讨论】:

  • 使用聚合。
  • 您使用的是哪个版本的 MongoDB?您的预期输出甚至是有效的 JSON 吗?您的意思是输出具有单个元素的数组吗,例如 ['http://localhost/public/Images/okro.jpg'],因为 {'http://localhost/public/Images/okro.jpg'} 不是有效的 JSON。
  • 正是我想要的。 @chridam。我正在远程连接到 Mlab.com

标签: javascript node.js mongodb


【解决方案1】:
var mongoose = require('mongoose');
var Schema = mongoose.Types.ObjectId;
var condition1 = { $match: { 'twitter':  { $eq: 0 }  } };    
var condition2 = { $match: { '_id':  { $eq: 0 }  } };
var condition3 = { $match: { '_id':  { $eq: Schema('11111111111111111') }  } };
var condition4 = { $match: { '__v':  { $eq: 0 }  } };
var project = { "$project": { 
                        "imgs": '$meme.imgs'                            
                    }
        };
user.find({}, {condition1,condition2,condition3,condition4,project}, function (err, result) {

})

【讨论】:

    【解决方案2】:

    如果不需要重复值,可以使用distinct

     db.collection.distinct('meme.imgs')
    

    【讨论】:

      【解决方案3】:

      您可以简单地解析结果。更新答案。

      user.find({},{_id: 0,details:0,name:0 },function(err, docs){
        docs.forEach(function(u) {
              u=JSON.parse(JSON.stringify(u))
              console.log(u.meme); 
        });
      });
      

      【讨论】:

      • 您的答案是返回“forEach”不是函数。
      • 对不起,我的错误更新了答案。如果您认为它按预期工作,请投票。
      • 嘿@dev9,我如何使用 ejs 将它呈现给前端?谢谢,您的回答有效。
      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 2018-04-17
      • 1970-01-01
      • 2017-10-07
      • 2017-01-29
      • 2012-10-19
      • 2019-03-11
      • 2019-07-28
      相关资源
      最近更新 更多