node.js - 如何在 MongoDB 中以对象格式保存或获取数据
问题描述
当我执行获取用户模型的获取请求时,我正在获取对象数组。
[ { followers: [],
followings: [],
posts: [],
_id: 5bb04fccnkj8a813e6,
firebase_id: 'cBeDoamGaiH3',
name: 'Sujoy Saha',
__v: 0 } ]
但我希望它采用以下格式。即。嵌套对象格式。
{ followers: [],
followings: [],
posts: [],
_id: 5bb04fccnkj8a813e6,
firebase_id: 'cBeDoamGaiH3',
name: 'Sujoy Saha',
__v: 0 }
这是我的用户架构
const userSchema = new mongoose.Schema({
firebase_id:{
type: String,
required:true
},
name:{
type: String,
required: true
},
followers:[
{
type: String
}
],
followings:[
{
type: String
}
]
});
我必须为此做出什么改变?
解决方案
方案本身很好。您正在使用的获取请求可能find
会返回数组中的多个文档。这就是为什么你会看到一个数组包裹着你的对象。尝试使用findById
orfindOne
获取单个文档,它将作为object
而不是返回array
推荐阅读
- webpack - 如何使用 Webpack / Laravel 调试生产 Vue.js 2 编译代码
- java - 错误:在减去 Integer 和 int 时,二元运算符“-”的操作数类型错误
- android - AlertDialog setContentView 不工作 API22
- javascript - 通过 npm (nodejs) 管理不同的代码库 (github repos)
- android - 阻止根用户安装我的应用程序
- sap - BO - 派生表中的对象
- sql - Oracle:将 WITH 子句子查询提取到流水线的链式函数中;效率比较
- php - 循环图像添加 laravel 控制器
- html - 没有当前目录的相对路径
- amazon-web-services - Amazon S3 文件上传有时会使用 Java sdk 失败