首页 > 解决方案 > 解构 mongoose 文档

问题描述

在我的项目中使用猫鼬,我遇到了一个问题。我想找到所有具有这种键值对的文档role: USER。我可以获取文档列表,但无论我如何尝试,我都无法从中获取特定字段的值。
这是我的代码:

  const getUsersList = async () => {
  const users = await userModel.find({ role: USER });

  //also I truing:
  //In each case, I get undefined
  const users = await userModel.find({ role: USER }).userName;
  ////
  const users = await userModel.find({ role: USER }).exec();
  ////
  Document.prototype.toObject(users);
  ////
  JSON.stringify(users).userName
}

请求肯定会得到文件,因为console.log(users)列出了文件。

    [
  {
    _id: new ObjectId("618b1a587d57e9c8e78865e1"),
    userName: 'Username1',
    name: 'Fullname1',
    email: 'email1@gmail.com',
    password: 'Password1',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  },
  {
    _id: new ObjectId("618b1a6e7d57e9c8e78865e5"),
    userName: 'Username3',
    name: 'Fullname2',
    email: 'email2@gmail.com',
    password: 'Password2',
    status: 'INVITED',
    role: 'USER',
    __v: 0
  }
]

从猫鼬的文档来看,我做的一切都是正确的。还建议使用 将文档转换为对象toObject(),但 mongoose 没有找到请求
Моя схема 的这种方法:

  const userSchema = new Schema(
  {
    userName: { type: String, unique: true, required: true },
    name: { type: String, required: true },
    email: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    confirmationCode: { type: String, required: false },
    status: { type: String, required: true, default: STATUS.INVITED },
    role: { type: String, required: true, default: USER },
  },
);

标签: javascriptmongodbmongoose

解决方案


这是一个数组,所以试图获取 userName 是行不通的。您需要获取特定元素。尝试这个:

const userResponse = await userModel.find({ role: USER })
const firstUserName = userResponse[0].userName

推荐阅读