Virtual getter for virtual populated · Issue #4832 · Automattic/mongoose

PHOTO EMBED

Thu Feb 16 2023 14:32:06 GMT+0000 (Coordinated Universal Time)

Saved by @jaimin #mongodb #getter #setter #virtual

const VoteSchema = new Schema({
  value: Boolean,
  obj: String,
  kind: String,
  user: String,
  voted: String
});

const PostSchema = new Schema({
  title: String
});

var virtual = PostSchema.virtual('voted', {
  ref: 'Vote',
  localField: '_id',
  foreignField: 'obj',
  justOne: true,
});

virtual.getters.unshift(v => !!v);

const Vote = mongoose.model('Vote', VoteSchema);
const Post = mongoose.model('Post', PostSchema);

co(function * () {
    // create post
  const post = new Post({
    title: 'post-1'
  });

  // create vote
  const vote = new Vote({
    value: true,
    obj: post.id,
    kind: Post.modelName,
    user: 'uid:1'
  });

  // store models to db
  yield [
    post.save(),
    vote.save()
  ];

  // populate related votes
  const r = yield Post.findById(post._id)
    .populate({path: 'voted', match: {user: 'uid:1', kind: Post.modelName}});

  console.log('r', r.toObject({ virtuals: true }));
  console.log(r.voted);
});
content_copyCOPY

https://github.com/Automattic/mongoose/issues/4832