Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose schema reference

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);
like image 762
Tam2 Avatar asked Feb 10 '13 10:02

Tam2


People also ask

What is ref in Mongoose schema?

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.

What is ref schema?

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.

What is Mongoose schema path?

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.

Is Mongoose schema based?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.


1 Answers

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 :)

like image 143
Benjamin Gruenbaum Avatar answered Sep 17 '22 11:09

Benjamin Gruenbaum