[英]Remove embedded document in mongoose
我是node.js和MongoDB的新手。 我正在使用Mongoose Library通過node.js訪問MongoDB。
我有兩個架構,書和作者。 作者belongs_to一本書和書has_many作者。
我的模式中有這個:
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' );
問題是,當我從作為嵌入Book的Author中刪除文檔時,它將被刪除而不檢查參照完整性。 我的情況是,如果作者文檔嵌入了Book,則無法刪除。 Mongoose會自動檢查書中嵌入的作者文檔嗎? 可能嗎? 那怎么樣?
您可以針對您提到的架構嘗試以下代碼。
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的更多信息(方法,回調)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.