gpt4 book ai didi

arrays - 将文档推送到 Mongoose 模型数组中的子文档中

转载 作者:太空宇宙 更新时间:2023-11-04 00:14:50 24 4
gpt4 key购买 nike

在我的公司架构中,我有一个已发布的职位,其类型为数组,并将保存子文档

companySchema.js

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

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

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

最佳答案

我不知道你们公司的架构,但是如果你想将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();
});
});

关于arrays - 将文档推送到 Mongoose 模型数组中的子文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com