javascript - 解构 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 },
},
);
解决方案
这是一个数组,所以试图获取 userName 是行不通的。您需要获取特定元素。尝试这个:
const userResponse = await userModel.find({ role: USER })
const firstUserName = userResponse[0].userName
推荐阅读
- nosql - Oracle NoSQL 数据库索引扫描:如何建立边界
- vba - 如何创建字体对象vba
- python - 当我在我的 android 槽 Buildozer 上构建 Kivy 应用程序时收到 ReferenceError
- flutter - 如何更改文本字段中的值并将其显示在另一个屏幕上(颤振)?
- html - CSS,选择特定的类和类型
- ruby-on-rails - MessagesController#create 中的 ActiveModel::UnknownAttributeError
- node.js - 不断扩大节点内存有什么副作用?
- c++ - 项目之间的 SQLCHAR(或 SQL 函数)不一致
- ajax - 网页抓取初学者。AJAX POST 请求不起作用
- c# - 如何在 C# 中复制 Postman POST 请求