问题
I have a requirement for setting a TTL on a collection of Docs in my app but also need those docs to be referenced by another collection and am unsure how this would work?
Does setting a TTL on a document remove that document from all other reference docs when it is expired or would I have to write a backend process myself and not use mongoDb's TTL indexes?
An example schema of the functionality I would want :
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
createdAt: { type: Date, expires: 60*60*24 },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
So after a Day the Story doc would expire and i would need the ref to that story to expire from the person
回答1:
The built-in TTL doc expiration has no support for removing references to expired docs.
You'll need to provide that functionality in your own code if you need it.
回答2:
You cannot handle this with TTL indexes. You could use a cron job/scheduled task to remove old documents.
I'd suggest you read this, a nice lightweight way of implementing background processes on MongoDb.
来源:https://stackoverflow.com/questions/22808931/ttl-expiration-of-mongoose-referenced-document