简体   繁体   English

如何使用Mongoose将值推入MongoDB中嵌入式文档中的数组?

[英]How do I $push a value to an array within an embedded document in MongoDB using Mongoose?

It seems this may be an open issue with MongoDB, https://jira.mongodb.org/browse/SERVER-831 , but I'm not sure if there's actually a solution and I'm just thinking about and researching things in the wrong way. 看来这可能是MongoDB的未解决问题, https://jira.mongodb.org/browse/SERVER-831 ,但是我不确定是否确实有解决方案,我只是在考虑和研究其中的内容。错误道。

Here is a subset of my schema: 这是我的架构的一个子集:

var myModel = new mongoose.Schema({

  arrayA: [{
    subArrayA: [{
        fieldA: String
    }],
    subArrayB: [{
        fieldB: String
    }]
  }],

});

I want to update subArrayA by pushing a value into it. 我想通过将值推入其中来更新subArrayA。 I've tried doing this in various ways with no success. 我尝试过以各种方式进行此操作,但没有成功。 This is the simplest attempt: 这是最简单的尝试:

myModel.findByIdAndUpdate(req.mymodel.arrayA.id(req.params.id), {
        $push: {
            subArrayA: {
                fieldA: valA
            }
        }
}, function(err) {
     // some stuff
});

This works fine when pushing directly to arrayA. 直接推送到arrayA时,此方法工作正常。 For example, the code below executes the way I'd hope - by pushing a value into arrayA: 例如,下面的代码执行我希望的方式-通过将值推入arrayA:

myModel.findByIdAndUpdate(req.mymodel.id, {
    $push: {
        arrayA: {
            fieldA: valA
        }
    }
}, function(err) {
     // some stuff
});

It seems you are looking for "dot notation" . 看来您正在寻找“点符号” This is a way of specifying sub-elements of objects without specifying the whole thing. 这是一种指定对象子元素而不指定整个事物的方法。

But you did specify an actual model you your schema did you not: 但是您确实指定了一个实际模型,而您的架构没有:

var Model = mongoose.model( "Model", myModel );
mongoose.connect('mongodb://localhost/test');

Model.findByIdAndUpdate(req.mymodel.arrayA.id(req.params.id), {
        "$push": {
            "arrayA.subArrayA": {
                "fieldA": valA
            }
        }
}, function(err) {
     // some stuff
});

So now you can notate an update without overriding the whole object at a given level. 因此,现在您可以在不覆盖给定级别的整个对象的情况下进行更新。

I was able to get this working with the MongooseArray method 'push'. 我能够使用MongooseArray方法“ push”来工作。

req.mymodel.arrayA.id(req.params.id).subArrayA.push({fieldA:ValA});

req.mymodel.save(function (err) {
    // some stuff
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM