Reputation: 617
I'm using mongoose and have two schemas, a user
and a album
UserSchema = new mongoose.Schema
name:
type: String
required: true
albums: [
type: mongoose.Schema.Types.ObjectId
ref: 'Album'
]
, collection : 'gallery'
UserModel = mongoose.model 'User', UserSchema
AlbumSchema = new mongoose.Schema
name:
type: String
required: true
unique: true
owner:
type: mongoose.Schema.Types.ObjectId
ref: 'User'
# ....
, collection : 'gallery'
AlbumModel = mongoose.model 'Album', AlbumSchema
Of course AlbumModel has some other properties like created_time
or modified_time
and of course images
.
Every user is the owner of one or more albums. For performance reasons I want to store a reference of all albums on the user model (is this a dbref
?). In additionn to the ObjectId I want to store the album name which is the most frequently used property to read next to the id. The result should look something like (as e.g. json):
{
"name": "John Doe",
"albums": [
{
"id": "1234567890",
"name": "Sample album"
},
{
"id": "9876543210",
"name": "Sample album 2"
}
]
}
Is this possible using mongoose? Is the album name in the user model autoupdated if it's changed (which should happen very rarely)?
Upvotes: 0
Views: 521
Reputation: 146064
For performance reasons I want to store a reference of all albums on the user model (is this a dbref?
Yes, a DbRef is just a property in a document that is the ObjectId of a different document.
Is this possible using mongoose?
Yes, you can define this schema like this:
UserSchema = new mongoose.Schema
name:
type: String
required: true
albums: [{
id: {
type: mongoose.Schema.Types.ObjectId
ref: 'Album' },
name: String
]
Is the album name in the user model autoupdated if it's changed (which should happen very rarely)?
Nope, but you can use a mongoose postSave hook on the Album schema to keep this denormalized data in sync.
Upvotes: 1