node.js - 如何通过nodejs更新mongoDB中的嵌套对象文档?
问题描述
这是我的模型:
const FamilySchema = new Schema(
userId: {
type: Schema.Types.ObjectId,
ref: "User",
default: null
},
familyLocation: {
type: String,
trim: true,
default: null
},
father: {
name: {
type: String,
trim: true,
default: null
},
status: {
type: String,
trim: true,
default: null,
enum: [null, 'Employed', 'Business']
}
},
mother: {
name: {
type: String,
trim: true,
default: null
},
status: {
type: String,
trim: true,
default: null,
enum: [null, 'Employed', 'Business']
},
},
nativePlace: {
type: String,
trim: true,
default: null
},{
timestamps: true})
现在我想更新它的任何字段。到目前为止,这是我的 API:
const UpdateFamilyDetails = async (req, res, next) => {
try {
let queryObject = req.body
let filteredObject = {}
let id = req.user.id
//Remove null fields of the req.body object
for (const key in queryObject) {
if (`${queryObject[key]}` != 'null') {
filteredObject[key] = `${queryObject[key]}`
}
}
let finalObject = ModifyObject(filteredObject)
const result = await FamilyInfo.findOneAndUpdate({ userId: id },
{ $set: { finalObject }}, { new: true }).exec()
if ( !result ) {
return res.status(501).json({
status: false,
message: 'Internal server error'
})
}
res.status(201).json({ status: true, data: result });
} catch (error) {
if (error)
next(error)
}
}
我刚刚使用以下方法制作了finalObject :
const ModifyObject = obj => {
const { familyLocation, fatherName, fatherStatus,motherName, motherStatus, nativePlace } = obj
let data = {}
if (fatherName || fatherStatus) {
data.father = {}
if (fatherName) {
data.father.name = fatherName
}
if (fatherStatus) {
data.father.status = fatherStatus
}
}
if (motherName || motherStatus) {
data.mother = {}
if (motherName) {
data.mother.name = motherName
}
if (motherStatus) {
data.mother.status = motherStatus
}
}
if (familyLocation) {
data.familyLocation = familyLocation
}
return data }
那么将任何字段更新为 req.body 对象的正确有效方法是什么?请记住,如果req.body只有familyLocation 和 fatherName,那么只有familyLocation 和fatherName 值将被更新,其他值不会受到影响。谢谢。
解决方案
推荐阅读
- jmx-exporter - 在 jmx 导出器主机端口中使用 jmx 端口范围
- php - 选择 DISTINCT 返回重复数据 Laravel 8
- typescript - 为什么我的 CASL 能力在使用从 knex 返回的主题时不起作用?
- python - 如何“偷看”Flask 的 flash 消息?
- mysql - 如果我忘记了它并且还卸载了 MySQL,我该如何在 Windows 10 上重新安装 MySQL
- javascript - 无法在 firebase-messaging-sw.js 中导入 firebase 模块
- android - 在 Macbook 上的物理 android 上调试 Flutter 应用程序
- javascript - 如何添加使图像可以用鼠标滑动?
- python - 熊猫数据框中索引的内存使用背后的计算
- java - 无法修复“将库 'Gradle: com.badlogicgames.gdx:gdx-tools:1.10.0' 添加到类路径”(IntelliJ)