首页 > 解决方案 > 只从 mongoose.find 返回 _id

问题描述

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

这是用户模型

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"
    },  
 
]

标签: javascriptnode.jsmongoose

解决方案


不要同时使用 .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}`,
          });
        }
      }
}

推荐阅读