【问题标题】:only return _id from mongoose.find只从 mongoose.find 返回 _id
【发布时间】:2021-04-02 04:05:30
【问题描述】:

想要获取所有用户,但只返回 _ids 列表,检查了 db 中保存的数据,一切似乎都很好。

这是用户模型

let UserSchema = new mongoose.Schema({
  firstName: {
    type: String,
    minlength: 3,
    trim: true,
  },
  lastName: {
    type: String,
    minlength: 3,
    trim: true,
  },
  biography: {
    type: String,
    minlength: 5,
    trim: true,
  },
    });

 UserSchema.methods.toJSON = function () {
   let user = this;
   let userObject = user.toObject();

   return _.pick(userObject, ["_id", "firstName", "email"]);
 };

这是我的控制器功能

const controller = {
    fetchUsers :async (_req, res) => {
        try {
            await User.find({})
            .then((users) => {
              res.status(200).send(users);
            })
            .catch((err) => {
              res.status(400).send(err);
            });
        } catch (error) {
          res.status(400).json({
            Error: `something is wrong. ${error}`,
          });
        }
      }
}

结果是我在邮递员中测试的是:

[
    {
        "_id": "5fe26ba0d290a216c0fe6d5d"
    },
    {
        "_id": "5fe26c8e40ca9a06b8c96259"
    },  
 
]

【问题讨论】:

  • 所以你想要一个字符串数组而不是对象数组?你从来没有真正说出问题所在。
  • @epascarello 我想返回用户的全部数据,例如名字和姓氏和传记
  • 我不是猫鼬专家,所以只是在黑暗中刺伤我。你会在以后的某个时候重新声明它吗?不知道你为什么使用let 而不是constUser 真的在使用UserSchema 吗?

标签: javascript node.js mongoose


【解决方案1】:

不要同时使用 .then 和 await 。试试这个。假设模型是正确的。

const controller = {
    fetchUsers :async (_req, res) => {
        try {
            const users=await User.find({}).exec()
            if(users){
              res.status(200).send(users);
            }
            else{
              res.status(404).send("no user found");
            };
        } catch (error) {
          res.status(500).json({
            Error: `something is wrong. ${error}`,
          });
        }
      }
}

【讨论】:

  • 你对 Promis 和 Async 的权利,我们不应该一起使用它们,我再次检查了我的模型,问题就在那里。
【解决方案2】:

问题是UserSchema.methods.toJSON方法没有任何email字段,如果我们想过滤我们的输出数据最好用mongoose.find({"condition"},{"fields"})过滤它

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 2019-02-26
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多