簡體   English   中英

findOneAndUpdate Mongoose 函數中的字符串文字問題

[英]String Literal Issue in findOneAndUpdate Mongoose Function

與此問題類似https://stackoverflow.com/questions/11183480/how-to-set-key-by-var-in-mongoose-node-js# =我無法在findOneAndUpdate函數中獲取字段變量。 它將它作為文字字段。 我試圖實施他們的解決方案,但沒有奏效。 我沒有收到錯誤,只是沒有更新任何內容。

var cat = new Cat();

var field = (req.body[1].type);

Cat.findOneAndUpdate({ 'sid': req.sessionID }, {$push: {field: req.body[0]}}, {'upsert': true, 'new': true}, function (err, data){

您需要使用方括號[]符號將對象屬性的“鍵”設置為變量中的值:

var cat = new Cat();

// Just use it in the below assignment instead
//var field = (req.body[1].type);

var update = { "$push": { } };
update.$push[req.body[1].type] = req.body[0];

Cat.findOneAndUpdate(
    { 'sid': req.sessionID },
    update,                      // and reference in here
    {'upsert': true, 'new': true}, 
    function (err, data){

這就是在 JavaScript 中動態分配鍵的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM