我目前有兩個系列:旅游和團體。由于游覽可以有多個組,我想計算具有特定游覽 ID 的所有組,并在我的游覽端點上提供此 ID。
Group = require("../models/groupModel");
var tourSchema = mongoose.Schema({
title: String,
currentSize: {type: Number, get: getCurrentSize},
...
});
function getCurrentSize(currentSize) {
var persons = 0;
Group.find({ tour: this.id }, function (err, groups) {
for (var i = 0; i < groups.length; i ) {
persons = groups[i].persons;
}
return persons;
});
}
但是,如果我使用這個 getter,則 currentSize 甚至不會回傳。如果我洗掉它,它將回傳存盤在檔案中的值。
有沒有辦法實作這一目標?我已經將其作為異步函式進行了嘗試,該函式會導致一些“查詢已執行”錯誤。
uj5u.com熱心網友回復:
好吧,我不知何故完全走上了錯誤的軌道。經過一些良好的睡眠后,我發現我需要的是虛擬機。
var tourSchema = mongoose.Schema({
title: String,
...
});
tourSchema
.virtual("currentSize", {
ref: "group", // The model to use
localField: "_id", // Find people where `localField`
foreignField: "tour", // is equal to `foreignField`
})
.get(function (group) {
var persons = 0;
for (var i = 0; i < group.length; i ) {
persons = parseInt(group[i].persons);
}
return persons;
});
在我的 tourController.js 中,我可以使用這樣的東西:
exports.index = async function (req, res) {
const tours = await Tour.find({})
.populate("currentSize")
res.json(tours);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378964.html
