我在猫鼬中设置了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'}]更多推荐
猫鼬嵌套文档
发布评论