猫鼬嵌套文档

编程入门 行业动态 更新时间:2024-10-19 00:24:59
本文介绍了猫鼬嵌套文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在猫鼬中设置了2种模式:

I have 2 schemas set up in mongoose:

var Job = new mongoose.Schema({ title: String, budget: Number }); var JobModel = mongoose.model('Job', Job); var Customer = new mongoose.Schema({ name: String, jobs: [Job] }); var CustomerModel = mongoose.model('Customer', Customer);

客户模型具有一系列的工作模型.

The Customer model has an array of job models.

我要添加新工作,如下所示:

I am adding a new job as follows:

app.post('/api/jobs', function(req, res){ var job = new JobModel({ title: req.body.title, budget: req.body.budget }); job.save(function(err){ if(!err){ CustomerModel.findById(req.body.customerId, function(err, customer){ if(!err){ customer.jobs.push(job); customer.save(function(err){ if(!err){ return console.log('saved job to customer'); } }); } }); return console.log('created job'); } else { return console.log(err); } }); return res.send(job); });

当我添加新工作并获得所有我认为正确的客户时:

When I add a new job and GET all the customers I get which I think is correct:

[{ "__v": 1, "_id": "50f85695771aeeda08000001", "name": "Customer1", "jobs": [ { "_id": "50fad6985edd968840000002", "budget": 100, "title": "job1" } ] }, ...]

现在,如果我更新作业1,并获取所有作业,则作业1已更新(预算现在为500)

Now if I update job1, and GET all the jobs, job 1 has been updated (budget is now 500)

[{ "title": "job1", "budget": 500, "_id": "50fad6985edd968840000002", "__v": 0 }, ...]

但是客户作业数组中的job1保持不变.

but the job1 in the customers job array remains unchanged.

[{ "__v": 1, "_id": "50f85695771aeeda08000001", "name": "Customer1", "jobs": [ { "_id": "50fad6985edd968840000002", "budget": 100, "title": "job1" } ] }, ...]

因此,我是否需要搜索Customer1的作业数组并找到job1作业并在每次更新或删除时也进行更新,或者我完全以错误的方式完成了整个嵌套工作?

Do I therefore need to search the Customer1's job array and find the job1 job and update that also every time I update or delete or am I totally doing the whole nesting thing the wrong way?

我知道客户中的工作数组是一个对象数组,但我认为它们可能只是工作的参考副本而不是重复对象?

I get that the jobs array in customer is an array of objects but I thought that they may be some how just a reference copy of the job rather than a duplicate??

推荐答案

如果您在此处使用Job文档的嵌入式数组,则它们是完全独立的副本,由您决定是否与它们保持同步单独的jobs集合.

If you use an embedded array of Job documents as you are here, they're completely independent copies and it's up to you to keep them in sync with the separate jobs collection.

替代方法是让Customer的jobs字段包含对'Job'的ObjectId引用数组,然后使用Mongoose的查询人口以根据需要按需填充.

The alternative is to have the jobs field of Customer contain an array of ObjectId references to 'Job' and then use Mongoose's query population to populate them on-demand, as needed.

jobs: [{type: Schema.Types.ObjectId, ref: 'Job'}]

更多推荐

猫鼬嵌套文档

本文发布于:2023-11-22 13:32:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617611.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!