2017-10-12 12 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 dbを照会することができます。 Entity.update()

関連する問題