如何编辑猫鼬中的嵌套对象

时间:2019-06-12 10:50:38

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

当前,我能够编辑未嵌套的对象。我想同时编辑父对象和嵌套对象的属性。如何使用猫鼬来做到这一点。

修改路线:-

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);

在邮递员中,如果我只是想编辑phoneNumber,我会通过

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

1 个答案:

答案 0 :(得分: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);

祝你好运。