Mongoose.js - population and additional fields?
Asked Answered
I

1

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

Incest answered 1/4, 2015 at 15:57 Comment(2)
Can you edit your question and show what the Movie model mongoose schema is like?Lashonlashond
Oh, yes, just edited thatIncest
I
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')

Intinction answered 1/4, 2015 at 17:22 Comment(6)
I know that, but the question is not about that.Incest
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 answerIntinction
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 movieIncest
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? :)Incest
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!Incest
how to do the insert if I'm using above schemaIbadan

© 2022 - 2024 — McMap. All rights reserved.