Данные не попадают в основной массив схемы mongoose - PullRequest
0 голосов
/ 07 июня 2019

Я пытаюсь отправить данные дочерней схемы в пользовательскую схему, но она не помещается в массив, определенный в родительской схеме.

Это мой дочерний контроллер код: -

userr.save((err, doc) =>{

        if(!err){
            if(req.userData.role2 === 'admin') {
            console.log("saving successful");
            res.send(doc);
            Admin.findOneAndUpdate({ _id: req.userData.userId },{ 'admin.admins' : { $push: { users: userr }}},
              function (error, success) {
                if (error) {
                  console.log(error);
                }
                console.log(success);
              });
        }             
        }

Родительская схема: -

var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },  
    companyID:  {
                type: String,
                },              
    address :   {
                type: String,
                required: "Address can't be empty.",
                },
    contactDetails : {
                type: String,
                required: "Company contact number can't be empty.",
                },
    admins:     {
                        _id: mongoose.Schema.Types.ObjectId,
                        email :     {
                                    type: String,
                                    required: "Email can't be empty.",
                                    unique: true
                                    },
                        password:   {
                                    type: String,
                                    required: "Password name can't be empty."
                                    },
                        firstName : {
                                    type: String,
                                    required: "First name can't be empty."
                                    },
                        lastName : {
                                    type: String,
                                    required: "Last name can't be empty."
                                    },  
                        phoneNumber :   {
                                    type: String,
                                    required: "Reqired for further contact. Can't be empty."
                                    },
                        designation :   {
                                    type: String,
                                    required: "Designation can't be empty."
                                    },
                        verified: String,                               
                        role: String,
                        emailResetTokenn: String,
                        emailExpires: Date,
                        saltSecret: String,//this is user for encryption and decryption of password 
                        users:[ {type: mongoose.Schema.Types.ObjectId, ref: 'Userr'}]   
    }           
});
mongoose.model('Admin', adminSchema);

Поэтому я хочу поместить данные в массив users.Здесь Userr - это имя дочерней схемы mongoose.model('Userr' , userrSchema);.

Я вижу, что новый дочерний объект создан в новой коллекции, но не добавляется в родительскую Admin схему.Что я должен сделать, чтобы внести изменения?

РЕДАКТИРОВАТЬ: -

Это мой родительский контроллер схемы: -

var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.address = req.body.address;
    admin.contactDetails  = req.body.contactDetails;
    admin.admins = {
                    email : req.body.email,
                    password: req.body.password, 
                    firstName : req.body.firstName, 
                    lastName : req.body.lastName,
                    phoneNumber : req.body.phoneNumber,
                    designation : req.body.designation,
                    role : "admin",
                    verified :"false",
                    users : [] 
    };

1 Ответ

1 голос
/ 07 июня 2019

Я думаю, что проблема здесь: { 'admin.admins' : { $push: { users: userr } } }. Вы ссылаетесь на поле «admin.admins», но оно не существует, это просто «admins», и я думаю, что синтаксис также не верен. Также я не уверен, что Mongoose установит его правильно, передавая весь объект, но что вы действительно хотите вставить, так это идентификатор пользователя, поэтому я думаю, что ваш код должен быть:

Admin.findOneAndUpdate({ _id: req.userData.userId }, { $push: { 'admins.users': userr._id } }, function (error, success) {
    //...
});
...