【问题标题】:MONGODB: updating a nested array in a subdocumentMONGODB:更新子文档中的嵌套数组
【发布时间】:2017-10-12 08:09:24
【问题描述】:

我可以使用 $addToSet 更新文档中的数组,但我想更新文档数组中的数组。

我的架构:

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.特定值的关键字

提前致谢!!!

【问题讨论】:

标签: javascript arrays mongodb mean-stack


【解决方案1】:
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()

【讨论】:

    猜你喜欢
    • 2016-11-23
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2013-03-19
    • 2014-09-23
    • 1970-01-01
    • 2017-06-05
    • 2013-08-12
    相关资源
    最近更新 更多