简体   繁体   English

猫鼬-保存时更新参考文档

[英]Mongoose - Updating a referenced Document when saving

If I have a Schema which has an Array of references to another Schema, is there a way I can update both Documents with one endpoint? 如果我有一个架构,该架构具有对另一个架构的引用的数组,是否可以用一个端点更新两个文档?

This is my Schema: 这是我的架构:

CompanySchema = new Schema({
  addresses: [{
    type: Schema.Types.ObjectId,
    ref: 'Address'
  }]
});

I want to send a Company with the full Address object to /companies/:id/edit . 我想将具有完整Address对象的Company发送到/companies/:id/edit With this endpoint, I want to edit attributes on Company and Address at the same time. 使用此端点,我想同时编辑“ Company和“ Address上的属性。

In Rails you can use something like nested attributes to do one big UPDATE call, and it will update the Company and update or add the Address as well. Rails您可以使用诸如嵌套属性之类的功能来进行一个大的UPDATE调用,它会更新Company 以及更新或添加Address

Any idea how would you do this in Mongoose ? 您知道如何在Mongoose执行此操作吗?

Cascade saves are not natively supported in Mongoose ( issue ). Mongooseissue )本身不支持级联保存。

But there are plugins (example: cascading-relations ) that implement this behavior on nested populate objects . 但是有一些插件(例如: cascading-relations )在嵌套的填充对象上实现此行为。

Take in mind that mongodb is not a fully transactional database , and the "big save" is achieved with various insert()/update() op calls and you (or the plugin) have to handle errors and rollback. 请记住,mongodb 并不是一个完全事务性的数据库 ,并且通过各种insert()/ update()op调用实现了“大节省”,您(或插件)必须处理错误和回滚。

Example of cascade save: 级联保存的示例:

company.save()
  .then(() => Promise.all(company.addresses.map(address => {
    /* update fkeys if needed */
    return address.save()
    }))
  .catch(err => console.error('something went wrong...', err))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM