简体   繁体   中英

Saving a modified document (with a modified subdocument array) in Mongoose model

The code I currently have is:

User.findOne(
    {
        "subUsers.email" : userEmail
    },
    {
        subUsers : {
            $elemMatch: {
                email : userEmail                            }
        }
    },
    function(err, user){
        if(user){
            var information = user.subUsers[0].information.id(id);

            information.arrayA.push({someId : "something"});

            user.save(callback(err)); // Also tried information.save()
                                      // without luck
        }

        callback(err);
    }
);

This doesn't return any kind of error, but when I check the DB, the new array element hasn't been pushed (the whole document is intact).

Any help would be much appreciated. Thanks!

You should probably check out the first faq, here: http://mongoosejs.com/docs/faq.html

Mongoose doesn't create getters/setters for array indexes; without them mongoose never gets 
notified of the change and so doesn't know to persist the new value. The work-around is to 
use [MongooseArray set][1] available in Mongoose >= 3.2.0.

So in your case, you want to add this third line

var information = user.subUsers[0].information.id(id);
information.arrayA.push({someId : "something"});
user.subUsers.set(0, information);

Or something like that.

As of today, Mongoose is currently not prepared for multilevel nesting in an atomic way.

Therefore, even if it's going back to a kind-of relational database, in this case it's better to split the nesting into at least 2 collections, and reference using the automatically generated ObjectId.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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