[英]Mongoose add asynchronous virtual field
I have a Recipe
model and a Like
model.我有一个
Recipe
模型和一个Like
模型。 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.我想在
Recipe
模型上设置一个虚拟字段,以便在我从数据库中获取某个食谱时获得该Recipe
数。 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
.这不能直接回答您的问题,但如果 virtuals 无法处理
async
函数,您始终可以在RecipeSchema
保留对 Like 对象数组的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.然后,您将在文档中拥有一个数组,您可以参考 的长度来计算点赞数,如果您需要点赞文档中的实际信息,您可以稍后
populate
它们。
Note: You would have to write logic to append new Likes to the likes
array in the proper Recipe.注意:您必须编写逻辑以将新的 Likes 附加到正确 Recipe 中的
likes
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.