Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper pattern for nested schemas in Mongoose/MongoDB?

It seems logical to me to do something like the following:

var AvatarSchema = new Mongoose.Schema({
    type: String,
    url: String
});

var UserSchema = new Mongoose.Schema({
    avatars: [AvatarSchema],
    email: String,
    name: String,
    salt: String,
    token: String
});

var ThinUserSchema = new Mongoose.Schema({
    avatars: [AvatarSchema],
    email: String,
    firstname: String,
    lastname: String,
});

var QuestionSchema = new Mongoose.Schema({
    question: String,
    users: [ThinUserSchema]
});

Then later on. . .do something like the following:

var question = new Question({
    question: 'Wut?',
    users: users //where users is an array of instances of a user model of the UserSchema
});

Here I would expect the users section of the question to be populated with avatars, emails, firstnames and lastnames. . .however since the users/avatars already have _id, these are not persisted.

  • Deleting each of the _id from the user/avatars seems silly.
  • Explicitly setting up each user/avatar seems inefficient.
  • Switching to a mixed type, puts EVERYTHING in there, and requires markModified.

What is the proper pattern for these sorts of schemas?

Thanks!

like image 978
jbg Avatar asked Sep 08 '25 10:09

jbg


1 Answers

I believe you are correct in your assumptions, it's called Embedded documents in Mongoose, here is the example from the Mongoose documentation.

var Comments = new Schema({
    title     : String
  , body      : String
  , date      : Date
});

var BlogPost = new Schema({
    author    : ObjectId
  , title     : String
  , body      : String
  , date      : Date
  , comments  : [Comments]
  , meta      : {
        votes : Number
      , favs  : Number
    }
});

mongoose.model('BlogPost', BlogPost);

Disclaimer: I wouldn't necessarily put the comma before the items!

like image 58
Neil Avatar answered Sep 11 '25 03:09

Neil