gpt4 book ai didi

node.js - 如何编辑 Mongoose 中的嵌套对象

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:11 30 4
gpt4 key购买 nike

目前我可以编辑未嵌套的对象。我想编辑父对象和嵌套对象属性。我怎样才能使用 Mongoose 做到这一点。

编辑路线:-

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."]);
}
});

Controller :-

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 。我怎样才能编辑嵌套对象属性?我必须在编辑 route 进行哪些更改?

编辑添加架构

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,只需传递

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

最佳答案

您应该使用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);

祝你好运。

关于node.js - 如何编辑 Mongoose 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560407/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com