简体   繁体   中英

Mongoose add asynchronous virtual field

I have a Recipe model and a Like model. I want to set a virtual field on the Recipe model to get the number of likes on a recipe when I fetch it from the database. But it returns an empty object.

RecipeSchema.virtual('likeCount').get(async function () {
  const likes = await Like.find({ recipe: this._id });

  return likes.length;
});

This doesn't answer your question directly, but if virtuals can't handle async functions, you can always keep references to an array of Like objects in your RecipeSchema .

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const recipeSchema = Schema({
  ...
  likes: [{ type: Schema.Types.ObjectId, ref: 'Like' }]
  ...
});

Then you'll have an array in the document that you can refer to the length of for a count of likes, and you can populate them later if you need the actual information inside the Like documents.

Note: You would have to write logic to append new Likes to the likes array in the proper Recipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM