【问题标题】:_id or another field from JSON response Node js not excluded_id 或来自 JSON 响应节点 js 的其他字段未排除
【发布时间】:2019-09-11 10:07:17
【问题描述】:

我想在我的 node-express 应用程序中从 JSON API 获取数据结果时排除默认 _id 或两个字段(时间和计数)中的任何一个。我尝试了几种方法,但数据仍然显示我在 GET 响应中标记为排除的字段。在下面的代码中,我使用 _Id 作为示例,但我的数据库的每个字段都存在类似的问题。以下是我发现的一些不起作用的方法:

exports.get_all_clothing = (req, res, next) => {
    Clothing.find({}, {projection:{_id: 0}})
    .exec()
    .then(docs => {
        console.log(docs);
        res.status(200).json(docs);
    })       

      .catch(err => {
        console.log(err);
        res.status(500).json({
          error: err
        });
      });
}
                             AND

exports.get_all_clothing = (req, res, next) => {
    Clothing
    .find({}).project({ _id: 0 })
    .exec()
    .then(docs => {
        console.log(docs);
        res.status(200).json(docs);
    })       

      .catch(err => {
        console.log(err);
        res.status(500).json({
          error: err
        });
      });
}
                           AND

exports.get_all_clothing = (req, res, next) => {
    Clothing.find('-_id')
    .exec()
    .then(docs => {
        console.log(docs);
        res.status(200).json(docs);
    })       

      .catch(err => {
        console.log(err);
        res.status(500).json({
          error: err
        });
      });
}

每次我得到的结果都是

[ { _id: 5cb73
    time: '656
    count: 43,
    __v: 0 }, 
  { _id: 5cb73
    time: '155
    count: 60,
    __v: 0 }, 
  { _id: 5cb73
    time: '155
    count: 56,
    __v: 0 }, ....]

请帮忙。

【问题讨论】:

标签: node.js express mongoose


【解决方案1】:

试试这个:

exports.get_all_tweets = (req, res, next) => {
    Clothing.find({}, {_id: 0})
    .exec()
    .then(docs => {
        console.log(docs);
        res.status(200).json(docs);
    })       

      .catch(err => {
        console.log(err);
        res.status(500).json({
          error: err
        });
      });
}

【讨论】:

    【解决方案2】:

    您可以使用 query.select 来获得您想要的结果。

    exports.get_all_tweets = (req, res, next) => {
        Clothing.find()
        .select('-_id')
        .then(docs => {
            console.log(docs);
            res.status(200).json(docs);
        })       
    
          .catch(err => {
            console.log(err);
            res.status(500).json({
              error: err
            });
          });
    }
    

    【讨论】:

    • 仍然得到_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多