Is it possible to have a Schema to reference another Schema within Mongo?
I've got the below, where i would like the user in the Line schema to be a user from the UserSchema
var UserSchema = new Schema({
name: {type: String, required: true},
screen_name: {type: String, required: true, index:{unique:true}},
email: {type: String, required: true, unique:true},
created_at: {type: Date, required: true, default: Date}
});
var LineSchema = new Schema({
user: [UserSchema],
text: String,
entered_at: {type: Date, required: true, default: Date}
});
var StorySchema = new Schema ({
sid: {type: String, unique: true, required: true},
maxlines: {type: Number, default: 10}, // Max number of lines per user
title: {type: String, default: 'Select here to set a title'},
lines: [LineSchema],
created_at: {type: Date, required: true, default: Date}
});
var Story = db.model('Story', StorySchema);
var User = db.model('User', UserSchema);
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
A schema can reference another schema using the $ref keyword. The value of $ref is a URI-reference that is resolved against the schema's Base URI.
You can think of a Mongoose schema as the configuration object for a Mongoose model. A SchemaType is then a configuration object for an individual property. A SchemaType says what type a given path should have, whether it has any getters/setters, and what values are valid for that path.
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
Yes it is possible
var LineSchema = new Schema({
user: {type: Schema.ObjectId, ref: 'UserSchema'},
text: String,
entered_at: {type: Date, required: true, default: Date}
});
Also a remark, why are you calling them LineSchema
and UserSchema
? You can call them Line
and User
, they represent a line and a user after all :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With