首页 > 解决方案 > _id 或来自 JSON 响应节点 js 的其他字段未排除

问题描述

我想在我的 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.jsexpressmongoose

解决方案


尝试这个:

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
        });
      });
}

推荐阅读