【问题标题】:Remove embedded document in mongoose删除 mongoose 中的嵌入文档
【发布时间】:2013-03-24 18:22:24
【问题描述】:

我是 node.js 和 MongoDB 的新手。我正在使用 Mongoose 库通过 node.js 访问 MongoDB。

我有两个模式,书和作者。 Author belongs_to a Book 并且 Book has_many Author。

我的架构中有这个:

var mongoose = require( 'mongoose' );
var Schema   = mongoose.Schema;

var Book = new Schema({
    title : String,
    isbn : String,
    authorId : [{ type: Schema.Types.ObjectId, ref: 'Author' }],
    updated_at : Date
});

var Author = new Schema({
    name  : String,
    updated_at : Date
});

mongoose.model( 'Book', Book );
mongoose.model( 'Author', Author );

mongoose.connect( 'mongodb://localhost/library' );

问题是,当我从 Author 中删除嵌入 Book 的文档时,它会在不检查引用完整性的情况下被删除。我的情况是,如果 Author 文档嵌入在 Book 中,则无法删除。 Mongoose 会自动检查书中嵌入的作者文档吗?可能吗?那怎么办?

【问题讨论】:

  • 不,没有任何内置的参照完整性检查。但是,您可以通过 this answer 中的“删除”中间件添加它。

标签: javascript node.js mongodb mongoose


【解决方案1】:

您可以为您提到的架构尝试以下代码。

Author.pre('remove', function(next) {
    Author.remove({name: this.name, updated_at: this.updated_at }).exec();
    Book.remove({authorId : this._id}).exec();
    next();
});

更多信息SchemaObj.pre(method,callback)

【讨论】:

  • 这样我们就不需要在controller中写findOneAndDelete方法了?我的假设是正确的吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2018-07-24
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多