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);
});