如何使用猫鼬将用户架构的数据插入主架构

时间:2019-06-06 07:29:18

标签: node.js mongodb express mongoose mongoose-schema

这是我的新手,但没有获得如何将子模式数据插入父模式数组的方法。

我的子架构模型定义为:-

 //user model
    var userrSchema = new mongoose.Schema({
        email :     {
                    type: String,
                    required: "Email can't be empty.",
                    // unique: true
                    },
        password:   {
                    type: String,
                    required: "Password name can't be empty."
                    },
    });
mongoose.model('Userr' , userrSchema);

并且我已将父级(管理员)架构定义为:-

//define admin schema 
var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },
    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."
                                    },
                        users:[ userrSchema ]   
    }           
});

mongoose.model('Admin', adminSchema);

我在同一个模型文件中都定义了它们。我有一个 controller r来注册父模式:-

mongoose.model('Admin', adminSchema);


const Admin = mongoose.model('Admin');
var MongoClient = require('mongodb').MongoClient;

module.exports.registerAdmin = (req, res, next) =>{ 
    var admin = new Admin();
    admin.companyName = req.body.companyName;
    admin.admins = {
                    email : req.body.email,
                    password: req.body.password,
                    users : [] 
    }; 
admin.save((err, doc) =>{

从路由文件注册管理架构后:-router.post('/registerAdmin' , ctrlAdmin.registerAdmin)我得到的结果为:-

{
    "admins": {
        "email": "xyz@ing.com",
        "password": "$2a$10$juGvica8UTqtmyywnWQuKOo9KpqX9JeFfqy1n6GR4xDL2GMLM0hze",
        "users": []
    },
    "_id": "5cf8b54e66b45740ae68feac",
    "companyName": "ABC"
    "__v": 0
}

那么我将如何注册子模式并将其详细信息推入父模式users键中?请帮忙 。我是新来的,对如何插入子架构数据一无所知。

编辑:-使用管理员身份验证更新了保存功能

为子架构创建了控制器,但是在运行url之后没有任何反应:

    module.exports.registerUserr = (req, res, next) =>{ 

        var userr = new Userr();
        userr.email = req.body.email,
        userr.password = req.body.password, 
        userr.firstName = req.body.firstName, 
        userr.lastName = req.body.lastName,
        userr.phoneNumber = req.body.phoneNumber,
        userr.role = "user",
        userr.verified = "false"
        userr.save((err, doc) =>{

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

和在路线router.post('/registerUserr' ,checkAuth, ctrlUserr.registerUserr);

1 个答案:

答案 0 :(得分:0)

尝试用此替换保存功能

userr.save((err, doc) => {
  if (!err) {
    res.send(doc);
    Admin.findOneAndUpdate(
      { _id: req.body.id },
      { admins: { $push: { users: userr }}},
      function (error, success) {
        if (error) {
          console.log(error);
        }
        console.log(success);
      }
    });
  }
}