我在找最受欢迎的食谱。
我有两个相关的收藏:食谱和收藏。
注意事项:我已经仔细检查了集合、名称和ids。
在数据库本身中,favoriterecipes中的_recipe字段是string类型,而在recipes中它是ObjectId类型。(也许需要类型转换?即使我在“查找”示例中没有看到这样的事情)。
favoriteRecipe.js:
const mongoose = require("mongoose");
const Recipe = require("./recipe");
const User = require("./user");
const FavoritesRecipesSchema = new mongoose.Schema({
_recipe: { type: mongoose.Schema.Types.ObjectId, ref: Recipe },
_user: { type: mongoose.Schema.Types.ObjectId, ref: User },
});
module.exports = mongoose.model("FavoriteRecipe", FavoritesRecipesSchema);recipe.js:
const mongoose = require("mongoose");
const User = require("./user");
const RecipeScheme = new mongoose.Schema({
name: String,
ingredients: [String],
instructions: String,
image: String,
date: { type: Date, default: Date.now },
tags: [String],
_user: { type: mongoose.Schema.Types.ObjectId, ref: User },
});
module.exports = mongoose.model("Recipe", RecipeScheme);controller.js:
exports.popular = async function (req, res, next) {
try {
const popular_recipes = await favoriteRecipe.aggregate([
{
$group: {
_id: "$_recipe",
recipeCount: { $sum: 1 },
},
},
{ $sort: { recipeCount: -1 } },
{
$lookup: {
from: "recipes",
localField: "_id",
foreignField: "_id",
as: "recipe",
},
},
// { $unwind: "$recipe" },
// {
// $project: {
// _id: "$recipe",
// recipeCount: 1,
// },
// },
]);
res.json(popular_recipes);
} catch (error) {
next(error);
}
};响应输出:
[
{
"_id": "6053349353b5f5632986b2c2",
"recipeCount": 3,
"recipe": []
},
{
"_id": "6053349353b5f5632986b2c3",
"recipeCount": 2,
"recipe": []
},
{
"_id": "605603945b4aeb0d2458153e",
"recipeCount": 1,
"recipe": []
}
]发布于 2021-03-31 17:51:18
最后,我发现必须将id字符串转换为对象id。解决方案:
exports.popular = async function (req, res, next) {
try {
const popular_recipes = await favoriteRecipe.aggregate([
{
$group: {
_id: { $toObjectId: "$_recipe" },
recipeCount: { $sum: 1 },
},
},
{ $sort: { recipeCount: -1 } },
{
$lookup: {
from: "recipes",
localField: "_id",
foreignField: "_id",
as: "recipe",
},
},
{ $unwind: "$recipe" },
{
$project: {
_id: "$recipe",
recipeCount: 1,
},
},
]);
res.json(popular_recipes);
} catch (error) {
next(error);
}
};https://stackoverflow.com/questions/66885205
复制相似问题