如何从另一个模式中获取的 ID 数组中按 Id 查找文档?
How to find documents by Id from an Array of IDs taken from another schema?
我有 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);
如果我正在使用具有 "selected" 配方的函数,我如何才能使 Data.find() 在数据模式中仅匹配具有我在数据数组?
考虑到选择的食谱是'recipe',你可以这样做,
recipe.populate('data', function (err, recipe) {
// here recipe.data will have the array of data objects instead of just _ids
});
如果所选食谱是精简的或不是 mongoose 文档,这将不起作用
修复字段类型:
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});
}
});
我有 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);
如果我正在使用具有 "selected" 配方的函数,我如何才能使 Data.find() 在数据模式中仅匹配具有我在数据数组?
考虑到选择的食谱是'recipe',你可以这样做,
recipe.populate('data', function (err, recipe) {
// here recipe.data will have the array of data objects instead of just _ids
});
如果所选食谱是精简的或不是 mongoose 文档,这将不起作用
修复字段类型:
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});
}
});