【发布时间】:2019-05-13 20:11:55
【问题描述】:
我正在尝试使用 Express 动态更新我的 Mongoose 模型字段。
从 ajax 调用发送到路由处理程序的数据如下所示:
{ value: true, name: 'settings.follow.state' }
如您所见,该值是“点符号字符串”?我想用它作为字段选择器来更新我的 Mongoose 模型。
所以我的客户端 ajax 调用如下所示:
$("[name='settings.follow.state']").on("change",function () {
$.ajax({
url : window.location.pathname +"/update",
type : "POST",
contentType: "application/json",
data : JSON.stringify({
value : $(this).is(":checked"),
name : "settings.follow.state"
}),
success:function (response) {
console.log(response);
}
});
});
另外,使用 express 时是否需要 JSON.stringify 我的数据?
这是我的 Express 路由处理程序:
router.post("/:id/update",[
oneOf([
check("value","Field cannot be empty.").isBoolean(),
check("value","Field cannot be empty.").not().isEmpty()
]),
check("name","Missing name field.").not().isEmpty(),
],function (req,res,next) {
let errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).send(errors.array()[0].msg);
}
Profile.findOne({_id:req.params.id,user:req.user._id}, function (err,doc) {
if(err) return next(err);
if(doc !== null){
TwitterSettings.findOne({_id:doc.settings},function (err,doc) {
if(err) next(err);
if(doc !== null){
//HERE is where I would like to update the dynamic fields/values
doc.set(req.body.name,req.body.value);
//Tried with no avail :-(
// doc.set([req.body.name],req.body.value);
// doc.set(`${req.body.name}`,req.body.value);
doc.save(function (err,doc) {
if(err) return next(err);
if(doc !== null){
return res.status(200).json(doc);
}
return res.status(400).send("Could not update profile.");
});
}else{
return res.status(400).send("Could find profile settings to update.");
}
});
// TRIED findOneAndUpdate too
// TwitterSettings.findOneAndUpdate({_id:doc.settings},{$set:{[req.body.name] : req.body.value}},{"new":true},function (err,doc) {
// if(err) return next(err);
// if(doc !== null){
// return res.status(200).json(doc);
// }else{
// return res.status(400).send("Could not update profile.");
// }
// });
}else{
return res.status(400).send("Could find profile to update.");
}
});
});
我的 Mongoose 模式架构(以防万一你需要它):
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
followers : {type:Number,default:0},
followings : {type:Number,default:0},
follow:{
state : {type:Boolean,default:false},
},
un_follow:{
state : {type:Boolean,default:false}
},
follow_back:{
state : {type:Boolean,default:false}
},
});
const model = mongoose.model('TwitterSettings', schema);
module.exports = model;
我确信有比我更聪明的人可以为我指明正确的方向。
谢谢 卡尔
【问题讨论】:
-
尝试缩小您的问题范围。你问的太多了
标签: node.js mongodb express mongoose