【问题标题】:Express Mongoose use Dot Notated Field as Field to UpdateExpress Mongoose 使用点表示字段作为要更新的字段
【发布时间】: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


【解决方案1】:

好的,所以您有一个名为 TwitterSettings 的集合,并且您想要更新 follow.state 路径中的值。

我通常会使用nessy module

const nessy = require( "nessy" );

...

Profile.findOne({_id:req.params.id,user:req.user._id}, function (err,doc) {
   ...
   TwitterSettings.findOne({_id:doc.settings},function (err,doc) {
       ...
       nessy( req.body.name, req.body.value, doc );
       doc.save( function( err, doc ) {
           ...
       } );
       ...
   } ); 
   ...
} );

你应该记住的是req.body.name实际上包含settings.follow.state,所以你应该从req.body.name中删除它:

nessy( req.body.name.replace(/^settings\./, ""), req.body.value, doc );

编辑

实际上,根据评论,您可以简单地使用model.set() 和不带settings. 部分的点符号。

【讨论】:

  • 您好,感谢您的回复。我只是犯了一个愚蠢的错误,从对其进行排序的名称中删除了“设置”。几个小时试图找出原因?。
  • 啊,现在我看到 mongoose 可以使用 set 方法更新深层密钥 :) 谢谢。
  • 更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 2021-07-09
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 2018-04-19
相关资源
最近更新 更多