我有2个这样的猫鼬模式:
var RecipeSchema = new Schema({
type: String,
version: String,
data: [{type: Schema.ObjectId, ref: 'Data'}]
});
var Recipe = mongoose.model("Recipe", RecipeSchema);
var DataSchema = new Schema({
ex1: String,
ex2: String,
ex3: String
});
var Data = mongoose.model("Data", DataSchema);
如果我正在使用具有“选定”配方的函数,那么我该如何做Data.find()在数据模式中仅匹配我在数据数组中具有_id的数据?
答案 0 :(得分:1)
考虑到所选食谱是“食谱”,您可以这样做
recipe.populate('data', function (err, recipe) {
// here recipe.data will have the array of data objects instead of just _ids
});
如果所选食谱较瘦或不是猫鼬文档,这将不起作用
答案 1 :(得分:0)
修复字段类型:
data: {
type: [Schema.ObjectId],
ref: 'Data',
default: []
}
用法:
const Recipe = mongoose.model('Recipe');
router.get('/recipes', async (req, res) => {
try {
const recipes = await Recipe.find({}).populate('data').lean();
res.status(200).send(recipes);
}
catch (error) {
res.status(500).send({message: error.message});
}
});