如何更新 Mongoose 中的对象?

How Do I Update An Object in Mongoose?

我在使用猫鼬更新数据库中的数据时遇到了一些问题,因此在此先感谢您的帮助。

我每次都从包含不同字段集的动态表单发送一些数据...但是当我更新数据库中的数组时,它会更改这些字段。

这是我之前的控制器函数:-

exports.savePageContent = (req, res, next) => {
    const id = req.body.dest;  // getting page data document id
    delete req.body.dest;
    var arr = [];

    // When we are returning the same page each time after we submit the data for the particuklar section form then how are we supposed to redirect the user to next page once he is done doing all 

    var fieldKeys = Object.keys(req.body);
    for(let i = 0; i < fieldKeys.length; i++)
    {
        arr.push({fieldRef : fieldKeys[i], fieldValue : req.body[fieldKeys[i]]});
    }

    pageDataModel.findByIdAndUpdate(id, {pageData : arr}).exec(function(err, result) {
        if(err){
            console.log(err);
        }
        else { 
            console.log("data is inserted");
            req.flash('message', "Data Saved Successfully");
            
        }
    })

} 

我也尝试了一些更新,然后移动到这部分

这是我的新控制器功能:

exports.savePageContent = (req, res, next) => {
    const pageid = req.body.dest;  // getting page data document id
    delete req.body.dest;

    var fieldRefData = "";
    var fieldValueData = "";

    var fieldKeys = Object.keys(req.body);
    for(let i = 0; i < fieldKeys.length; i++)
    {
        fieldRefData = fieldKeys[i];
        fieldValueData = req.body[fieldKeys[i]];

       try{

        pageDataModel.update({id : pageid, "pageData.fieldRef" : fieldRefData}, {$set : {"pageData.$.fieldValue" : fieldValueData }}, {upsert : true}).exec(function(err, result) {
            if(err){
                console.log(err);
            }
            else { 
                console.log("data is inserted", result);
            }
        });

        req.flash('message', "Data Saved Successfully");

       }catch(e){
        console.log(e);
        req.flash('message', "error Occurred updating Data ");

       }
    }

    

}  

详细说明案例以便更好地理解:-

这是体内第一次出现的数据

[
  { fieldRef: 'sec1.1.h1', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.1.p', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.1.a', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.2.h2', fieldValue: 'this is the field value 1' }
]

这是第二次来的数据:-

[
  { fieldRef: 'sec2.1.h1', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.1.p', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.1.a', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.2.h1', fieldValue: 'this the field value 2' }
]

当我想要数据库中的两个数据但是当我发送第二个数据时,第一个更新为第二个,反之亦然..

这是场景的数据库镜像

this is the data in the document on the first operation

this is the data in the document on the second operation

我无法同时保留和更新它们...所以请帮助我...

这是我大部分时间遇到的错误,表示查询错误

MongoServerError: The positional operator did not find the match needed from the query.
    at /home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/operations/update.js:80:33
    at /home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/connection_pool.js:272:25
    at handleOperationResult (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/sdam/server.js:370:9)
    at MessageStream.messageHandler (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/connection.js:479:9)
    at MessageStream.emit (events.js:400:28)
    at processIncomingData (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
    at MessageStream._write (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:731:22) {
  index: 0,
  code: 2
}

此外,如果我无法清楚地说明我的情况,请发表评论,我会尽力解释得更清楚.. 提前致谢

$set 将替换键的新值。如果您使用第三个值,那么 $set 将替换第三个值,请使用 $push 而不是 $set 运算符。https://docs.mongodb.com/manual/reference/operator/update/push/

尝试使用 _id 而不是 id

pageDataModel.update({_id : pageid, "pageData.fieldRef"}) {

甚至 pageData._id 而不是 id

pageDataModel.update({'pageData._id' : pageid, "pageData.fieldRef"}) {

此外,你的id在查询中是string,但在数据库中是object id,所以请帮助。

pageDataModel.update({'pageData._id' : mongoose.Types.ObjectId(pageid), "pageData.fieldRef"}) {

我希望这能解决问题:

pageDataModel.updateOne({_id : "61d73f31cb5681b85618995a", "pageData.fieldRef" : "sec2.c" },{"$set" : {"pageData.$.fieldValue" : "Mkc" }}).exec(function(err, result) {
        if(err) throw err;
        else {
            console.log(result);
        }
    });