我是 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 会自动检查嵌入在书中的作者文档吗?可能吗?那怎么办?
最佳答案
您可以为您提到的架构尝试以下代码。
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) 的更多信息
关于javascript - 删除 mongoose 中的嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15781360/