首页 > 解决方案 > 如何通过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 值将被更新,其他值不会受到影响。谢谢。

标签: node.jsmongodbapiexpress

解决方案


推荐阅读