将文档推送到mongoose模型

时间:2017-12-04 11:45:19

标签: arrays node.js mongodb express mongoose

在我的公司架构中,我有一个发布的作业,它是类型数组,将保存子文档

companySchema.js

PostedJobs : [{
        JobName : { type: String, required : true},
        JobType : { type: String, required : true},
        JobLocation : { type: String, required : true},
        JobSalay: { type: String, required : true}
    }],

在我/公司路线中,我通过模型

中的Creator实体获得特定用户注册的所有公司

获取我使用的用户公司

  router.get('/',  isLoggedIn ,  function(req, res, next) {
    Company.find({'Creator': req.user.id}).then(function(companies) {
        res.render('Company', { "Companies" : companies });
    });
});

获得公司后,我想点击公司名称(独特)

访问特定的公司页面
router.get('/:name' , isLoggedIn , function(req , res , next) {
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
         res.render('dashboard',{
            "Company" : Company,
             errors : []
        });
    })
});

现在我想从POST路线向这个特定公司发布一份工作 我的req.body由JobName,JobType,JobLocation和JobSalary组成,我已经分配给一个特定的变量,现在应该如何将这个doc推送到数组

POST路线

router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
});

1 个答案:

答案 0 :(得分:1)

我不知道贵公司的架构,但如果你想将TellJobs添加到公司,你应该在其中定义一个数组字段。

router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
    // create the postedJob object
    var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalay:Salary};
    // find the company in DB and add the postedJob to its array of postedJobs
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
        company.postedJobs.push(postedJob);
        company.save();
    });
});