12

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);
Tam2
  • 1,337
  • 3
  • 16
  • 23

1 Answers1

25

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

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 4
    Does the value of `ref` matter? I've seen various answers where the `ref` text is irrelevant to any models or schemas. – Kenny Worden Jul 16 '15 at 15:50
  • https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose#comment63767182_18002078 links to http://mongoosejs.com/docs/index.html – TheNavigat Apr 07 '18 at 21:44