【问题标题】:Push document into sub document in array of mongoose model将文档推送到猫鼬模型数组中的子文档中
【发布时间】:2018-05-17 21:01:58
【问题描述】:

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

companySchema.js

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

在我的 /company 路线中,我通过模型中的Creatorentity 获取特定用户注册的所有公司

获取我使用的用户公司

  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 组成,现在我已将它们分配给特定变量,我应该如何将此文档推送到数组

发布路线

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
});

【问题讨论】:

    标签: arrays node.js mongodb express mongoose


    【解决方案1】:

    我不知道你们公司的架构,但是如果你想给公司添加 PostedJobs,你应该在里面定义一个数组字段。

    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) {
            //modify and save the object received via callback
            company.postedJobs.push(postedJob);
            company.save();
        });
    });
    

    【讨论】:

    • 我已经发布了数组类型的工作
    • PostedJobs : [{ JobName : { type: String, required : true}, JobType : { type: String, required : true}, JobLocation : { type: String, required : true}, JobSalay: { 类型:字符串,必需:true} }],
    猜你喜欢
    • 2015-06-08
    • 2017-01-11
    • 2016-06-05
    • 2020-07-10
    • 2020-03-17
    • 2015-06-26
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多