5

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

Vytautas Butkus
  • 5,365
  • 6
  • 30
  • 45

1 Answers1

10

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

jtmarmon
  • 5,727
  • 7
  • 28
  • 45
  • I know that, but the question is not about that. – Vytautas Butkus Apr 01 '15 at 18:10
  • what exactly is your question about, then? to me it sounds like you're asking how to get more fields than just the title back when you use `.populate`. that's not a very helpful way to respond to an incorrect answer – jtmarmon Apr 01 '15 at 19:02
  • When I'm adding reference to user model (reference of movie) I would like to store a timestamp when was that reference saved, i.e. to know when user watched that movie – Vytautas Butkus Apr 01 '15 at 19:03
  • I just tried that and it seems that it does not work. Is it supposed to work and I'm doing something wrong, or you try to guess the implementation? :) – Vytautas Butkus Apr 01 '15 at 20:11
  • Don't know what happened yesterday (probably it was already too late) but now in the morning after trying again - it seems to just be working as expected. Thank you very much! – Vytautas Butkus Apr 02 '15 at 06:41
  • how to do the insert if I'm using above schema – Arun jai Jan 16 '19 at 12:01