MongoDB:将数组添加到现有数组中 [英] MongoDB: Adding an array into an existing array

查看:87
本文介绍了MongoDB:将数组添加到现有数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将教师"数组添加到已经存在的校园"数组中.

I'm trying to add an "Instructors" array into an already existing "Camps" array.

层次结构看起来像这样:

The hierarchical structure looks something like this:

owner = {

    email : 'john.smith@gmail.com',
    password : 'mypassword',
    firstName : 'john',
    lastName : 'smith',

    camps : [ 

                {

                    name : 'cubs-killeen',
                    location : 'killeen',
                    manager : {name: 'joe black', email: '', password: ''},

                    instructors : [

                        {

                            firstName : 'bill',
                            lastName : 'jones',

                            classes : []                        
                        }, 

                        {

                            firstName : 'jill',
                            lastName : 'jones',

                            classes : [],

                        },

                    ],

                    students : []

                }
            ]
};

我在MongoJS上使用Node Express,并且能够成功添加所有者并添加阵营",但是,在"addInstructor"函数中,当我尝试将教师"添加到特定阵营时,出现问题.我没有收到任何错误消息,相反,它只是在camps数组中的项目之后追加了"Instructors"数组.

I am using Node Express with MongoJS and have been able to successfully add an owner and add "camps", however, in the "addInstructor" function, when I try and add "Instructors" to a particular camp that is when the problems occur. I get no error message, instead it simply appends the "Instructors" array AFTER the items in the camps array.

任何帮助将不胜感激.下面是我的完整代码,带有工作功能,然后是不起作用的代码,下面是我的mongodb输出(尽管有误):

Any help would be greatly appreciated. Below is my full code, with working functions and then the one that is not working and below that is my mongodb output (albeit wrong):

CampRepository = function(){};

CampRepository.prototype.addOwner = function(owner, callback){

    console.log(db);

    db.owners.save(owner, function(err, saved){
        if (err || !saved) {
            console.log('broke trying to add owner : ' + err);
            callback(err);
        } else {
            console.log('save was successful');
            callback(null, saved);
        }
    });
};


CampRepository.prototype.addCamp = function(ownerEmail, camp, callback){

    db.owners.update(
            {email: ownerEmail},
            {$push: {
                camps:{
                            name: camp.name,
                            location: camp.location,
                            managerName: camp.managerName,
                            managerEmail: camp.managerEmail,
                            managerPassword: camp.managerPassword,
                            managerPayRate: camp.managerPayRate,
                            instructors: [],
                            students: []
                        }
                    }
            }, function(err, saved){

                if (err || !saved) {
                    console.log('broke trying to add camp ' + err);
                    callback(err);
                } else {
                    console.log('save was successful');
                    callback(null, saved);
                }

    });

};


/*
    THIS IS THE ONE THAT DOESN'T WORK
*/
CampRepository.prototype.addInstructor = function(ownerEmail, campName, instructor, callback){

    db.owners.update(
            {email: ownerEmail, 'camps.name': campName},
            {$push: {
                        camps:{

                            instructors: {

                                firstName: instructor.firstName,
                                lastName: instructor.lastName,
                                email: instructor.email

                            },
                        }
                    }
            }, function(err, saved){

                if (err || !saved) {
                    console.log('broke trying to add camp ' + err);
                    callback(err);
                } else {
                    console.log('save was successful');
                    callback(null, saved);
                }

    });

};

输出

{ 
    "_id" : ObjectId("51c7b04d2746ef6078000001"), 
    "email" : "john.smith@gmail.com", 
    "firstName" : john, 
    "lastName" : smith, 
    "password" : "mypassword", 
    "camps" : [  
                {   
                    "name" : "cubs-killeen",     
                    "location" : "killeen",     
                    "managerName" : "bill jones",     
                    "managerEmail" : "bill@gmail.com",  
                    "managerPassword" : "secretpasscode",    
                    "instructors" : [ ],    
                    "students" : [ ] 
                },     
                {   "instructors" : {   "name" : "jon tisdale" } }
    ] 
}

推荐答案

您可能需要看一下

You might need to take a look at this. you can achieve this using dot.notation It's very powerfull way to find or update items in a larger array of document scheme. If you still not able to achieve this i would happy to provide you the following code...

我插入了新的所有者2

I've inserted a new owner2

owner2 = {

email : 'murali.ramakrishnan@gmail.com',
password : 'mypassword',
firstName : 'murali',
lastName : 'ramakrishnan',

camps : [ 

            {

                name : 'Rotary club',
                location : 'trichy',
                manager : {name: 'baskaran', email: 'baskaran@mit.edu', password: 'baskaran'},

                instructors : [

                    {

                        firstName : 'baskaran',
                        lastName : 'subbiah',

                        classes : []                        
                    }, 

                    {

                        firstName : 'david',
                        lastName : 'nover',

                        classes : [],

                    },

                ],

                students : []

            }
        ]};

如果您看到我们只需要按要求添加新的讲师... 首先将文档添加到集合中

If you see we just need to add a new instructor as requested... let first add the document to the collection

db.try.insert(owner2);

在这里您添加了一个新文档 现在,我将创建一个新的教师对象,以插入@newly创建的owner2

here you go you have added a new document now, i'm going to create a new instructor object to insert @newly created owner2

instructor1 = {
          firstName : 'lakshmi',    
          lastName : 'kanthan',
          classes : []
        };

上方是新教师的文档对象 您可以使用

above is the document object for new instructor you can perform this update in many ways, using mongodbs methods like

collection.update collection.findAndModify

collection.update collection.findAndModify

如果要在子文档中插入或更新任何值,我们需要使用点号(.)来查找并将子文档推入文档,此处为代码

if you want to insert or update any value to the sub-document we need to find using a dot.notation and push the sub-document to the document, here the code

db.try.update(
     {'camps.name': "Rotary club" },
     {
        $push: { 'camps.$.instructors' : instructor1 }
     }
)

上面的代码在讲师字段下插入一条新记录,就像在数组中它只是推送子文档一样

the above code inserts a new record under the instructor field as in the field an array it just pushes the sub-document

最终结果

{
"_id" : ObjectId("51c7b222c0468dc711a60916"), 
"email" : "murali.ramakrishnan@gmail.com",
"password" : "mypassword",
"firstName" : "murali",
"lastName" : "ramakrishnan",

"camps" : [ 

            {

                "name" : "Rotary club",
                "location" : "trichy",
                "manager" : {"name": "baskaran", "email": "baskaran@mit.edu", "password": "baskaran"},

                "instructors" : [

                    {

                        "firstName" : "baskaran",
                        "lastName" : "subbiah",

                        "classes" : []                        
                    }, 

                    {

                        "firstName" : "david",
                        "lastName" : "nover",

                        "classes" : [],

                    },
        {

                        "firstName" : "lakshmi",
                        "lastName" : "kanthan",

                        "classes" : [],

                    }

                ],

                "students" : []

            }
        ]};

这篇关于MongoDB:将数组添加到现有数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆