Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js - population and additional fields?

I want to add some additional data to UserModel like watchedMovies and I have following schema:

let userSchema = new Schema({
  watchedMovies: [{
    type: Schema.Types.ObjectId,
    ref: 'Movie'
  }]
})

and:

let movieSchema = new Schema({
  title: String
})

I was wondering is it possible to add any additional fields to watchedMovies object and store it along with ObjectId? I would like to add watchedAt date so when I'm populating watchedMovies with UserModel.find().populate('watchedMovies', 'title').exec(...) I would get something like:

{
  _id: ObjectId(UserId),
  watchedMovies: [{
    _id: ObjectId(...),
    title: 'Some title',
    watchedAt: TimeStamp
  }]
}

watchedAt attribute specifies when (Date object) reference was added to UserModel

Is it possible with mongoose and how should I change my schema?

Thank You

like image 898
Vytautas Butkus Avatar asked Apr 01 '15 15:04

Vytautas Butkus


1 Answers

Change your schema to

let userSchema = new Schema({
  watchedMovies: [{
    movie: {
        type: Schema.Types.ObjectId,
        ref: 'Movie'
    },
    watchedAt: Date
  }]
})

then you can populate by .populate('watchedMovies.movie')

like image 127
jtmarmon Avatar answered Oct 16 '22 08:10

jtmarmon