【问题标题】:How can I edit nested objects in mongoose如何在猫鼬中编辑嵌套对象
【发布时间】:2019-10-26 20:41:24
【问题描述】:

当前我能够编辑未嵌套的对象。我想编辑父对象和嵌套对象属性。我怎样才能使用猫鼬做到这一点。

编辑路线:-

router.put('/editUser/:userId', checkAuth, function (req, res, next) {
    if(req.userData.role2 === 'superadmin') {
    const id  = req.params.userId;
    const newUserData  = req.body;
    Admin.findOneAndUpdate({ _id: id }, {$set: newUserData}, { new: true }, (err, doc) => {
                if (err) return res.send(err.message);
                if (doc) return res.send(doc);

            })
    } else {
        res.status(401).send(["Not authorized. Only super admin can update details."]);
    }       
});

控制器:-

module.exports.register = (req, res, next) =>{  

    var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.address = req.body.address;
    admin.admins = {
                    firstName : req.body.firstName, 
                    lastName : req.body.lastName,
                    phoneNumber : req.body.phoneNumber,
    };

我有 响应 json 像这样:-

{
  "admins": {
            "firstName": "ABC",
            "lastName": "FF",
            "phoneNumber": "855599"
   },
  "_id": "5d008f5a287805414247bd33",
  "companyName": "ABC",
  "address" : "UAE"
  "__v": 0
}

我可以编辑 companyNameaddress 。我如何也可以编辑嵌套对象属性?我必须在编辑路线中进行哪些更改?

编辑添加架构

var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },  
    companyID:  {
                type: String,
                },
    address :   {
                type: String,
                required: "Address can't be empty."
                },
    admins:     {
                firstName : {
                            type: String,
                            required: "First name can't be empty."
                            },
                lastName : {
                            type: String,
                            required: "Last name can't be empty."
                            },  
                phoneNumber :{
                            type: String,
                            required: "Reqired for further contact. Can't be empty."
                            }
    }           
});
mongoose.model('Admin', adminSchema);

如果我想在 Postman 中编辑 phoneNumber,我只是通过了

网址:-localhost:3000/api/editUser/{id} 正文为"{phoneNumber": "0000000"}

【问题讨论】:

    标签: node.js express mongoose mongoose-schema put


    【解决方案1】:

    您应该使用async/await 来优化您的代码:

    router.put('/editUser/:userId', checkAuth, async function (req, res, next) {
        if(req.userData.role2 === 'superadmin') {
        const id  = req.params.userId;
        const newUserData  = req.body;
        let newData = await Admin.findOne({ _id: id }).exec();
        newData['admins'].firstName = 'new First Name'
        newData['admins'].lastName = 'new Last Name'
        newData['admins'].phoneNumber = 'new Phone Number'
        await newData.save();
        } else {
            res.status(401).send(["Not authorized. Only super admin can update details."]);
        }       
    });
    

    更新修复架构和路由器 你的Admin Shema 应该是:

    let adminSchema = new mongoose.Schema({
        companyName : {
                    type: String,
                    required: false
                    },  
        companyID:  {
                    type: String,
                    },
        address :   {
                    type: String,
                    },
        admins:     {
                    type : new Schema({
                    firstName : {
                                type: String,
                                required: true
                                },
                    lastName : {
                                type: String,
                                required: true
                                },  
                    phoneNumber :{
                                type: String,
                                required: true
                                }
                        })
                        }     
    });
    mongoose.model('Admin', adminSchema);
    
    

    祝你好运。

    【讨论】:

    • 但我没有硬编码它。我将如何在路线中提及它?你能编辑我的路线吗?
    • 当我在 POSTMAN 上测试它时它不起作用,虽然我不想要这种方法。您正在对编辑数据进行硬编码。我想通过输入法进行测试。并且在某些时候,如果嵌套结构的键列表增加,就会在硬编码中产生问题。
    • 在我的问题中添加到编辑中
    • 检查新的更新答案。您应该使用findOne 并仔细定义方案。也许删除checkAtuh 中间件进行测试。
    • 请使用新架构重试
    猜你喜欢
    • 1970-01-01
    • 2014-02-10
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2017-01-28
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多