如何删除子文件只有在过期使用mongoose?
从集合1中删除子文档时遇到问题,集合2中的文档过期。
我有像下面的车模式。
var cartSchema = new schema({ userName : {type: String, default: null}, total : {type: Number, default: 0}, qty : {type: Number, default: 0}, productId : {type: String, default: null}, createdAt : {type: Date, default: Date.now, expires: 7200} // expired in 2 hours });
在这里我有架构,保存cartSchema
相关的对象cartSchema
var merchantSchema = new schema({ seller : String, address : String, email : String, products : [ { title : String, ingredients : String, qty : Number, carted : [ { qty : Number, cartId : String, createdAt : {type: Date, default: Date.now} } } ], });
因为expireAt
查询自动运行,我不知道如何在购物车过期和删除时自动删除carted对象。
当cartSchema
id 123
购物车过期并被删除时,所以购物车中id 123
cartSchema
对象也将被删除。
如果我在merchantSchema createdAt : {type: Date, default: Date.now, expires: 7200}
添加了expires
属性merchantSchema createdAt : {type: Date, default: Date.now, expires: 7200}
,它会删除整个文档。
您不能使用TTL index
删除子文档。
一个解决方法可以通过改变你的数据模式通过population
如下
var merchantSchema = new schema({ seller : String, address : String, email : String, products : [productSchema], }); var Merchant = mongoose.model('Merchant', merchantSchema); var productSchema = new Schema({ title : String, ingredients : String, qty : Number }); var Product = mongoose.model('Product', productSchema); var cartSchema = new schema({ userName : {type: String, default: null}, total : {type: Number, default: 0}, qty : {type: Number, default: 0}, productId : {type: Schema.Types.ObjectId, ref: 'Product'}, createdAt : {type: Date, default: Date.now, expires: 7200} // expired in 2 hours });
然后,创build的createdAt
到期,然后cart
文档将被删除,并且没有与product
文档相关的购物车信息。