猫鼬中的投影字段没有参数

问题描述 投票:0回答:1

所以我有这个控制器功能,它使用没有投影参数的简单查找查询

exports.get_all_item = function(req, res) {
  Item.find({}, function(err, item) {
    if (err)
      res.send(err);
    res.json(item);
  });
};

[每次我在邮递员中运行请求时,都会得到空结果。当我在Express中打开调试模式时,我看到此查询是由猫鼬发送的

Mongoose: item_m.find({}, { projection: {} })

当我尝试在mongodb中运行此查询时,出现此错误

"message" : ">1 field in obj: {}",

如果我确实添加了投影参数,例如item_name,猫鼬发送此信息:

Mongoose: item_m.find({}, { projection: { item_name: 1 } })

并且在mongodb中运行该查询时,出现此错误

"message" : "Unsupported projection option: projection: { item_name: 1.0 }",

但是当我将查询更改为

db.item_m.find({}, { item_name: 1 } )

它工作正常,返回Im期望的结果。

Express,node.js和mongodb还是新手。这是mongodb和mongoose之间的版本问题吗?我对mongodb使用4.0.13,对mongoose使用5.8.3,但是从我的研究来看,这应该没问题。我在这里还缺少什么呢?或者我应该检查什么我可能错过的东西?预先感谢。

node.js mongodb express mongoose
1个回答
0
投票

我使用此方法获取所有查询。我已根据您的需要对其进行了调整。

exports.get_all_item = (req, res, next) => {
  Item.find()
    .select("item_name")
    .exec()
    .then(items => {
      if (items.length > 0) {
        res.status(200).json(items);
      } else {
        res.status(204).json({
          message: "No items available"
        });
      }
    })
    .catch(error => {
      next(error);
    });
};

希望有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.