2017-10-12 160 views
0

我能夠使用$ addToSet更新文檔內的數組,但我想更新文檔數組內的數組。MONGODB:更新子文檔中的嵌套數組

我的架構:

const mySchema1 = new Schema({ 
    myId : {type:String, unique:true}, 
    name : String, 
    entries : [{ 
     value : String, 
     keywords:[String] 
    }] 
}); 

routes.js

app.put('/api/entity',function(req,res){ 
    let model = new Entity(); 
    console.log(req.body); 
    model.collection.update({"myId":req.body.myId,"entries":req.body.entries},{$addToSet:{"entries":{$each:[req.body.entries]}}},function(err,entries){ 
     if(err){ 
      res.send(err); 
     }else{ 
      res.send(entries); 
     } 
    }) 
}); 

現在我想更新(如果存在)/插入(如果不存在), 1.價值 2。特定值的關鍵字

在此先感謝!

+0

https://stackoverflow.com/questions/23470658/mongodb-upsert-sub-document這可能與您的問題有關 – Sridhar

回答

0
var entries = req.body.entries; 
// match ALL of the documents whose `entires` attribute contains ALL `req.body.entries` 
var query = {"myId":req.body.myId, "entries": {$all: entries}}; 

// match SOME of the documents whose `entires` attribute contains SOME `req.body.entries` 
// var query = {"myId":req.body.myId, "entries": {$some: entries}}; 

// ADD all `req.body.entries` to the matched documents 
var update = {$addToSet:{"entries":{$each:[entries]}}; 

// Create a new matching document if one doesn't already exeist 
var options = {upsert = 1}; 


app.put('/api/entity',function(req,res){ 
    let model = new Entity(); 

    console.log(req.body); 

    model.collection.update(
     query, 
     update, 
     options 
    },function(err,entries){ 
     if(err){ 
      res.send(err); 
     }else{ 
      res.send(entries); 
     } 
    }) 
}); 

順便說一句,你可以用一個簡單的語法查詢您Entity分貝。 Entity.update()