Node.js 如何从另一个模式的Id数组中按Id查找文档?
我有两种猫鼬模式,如下所示:Node.js 如何从另一个模式的Id数组中按Id查找文档?,node.js,express,vue.js,mongoose,mongoose-schema,Node.js,Express,Vue.js,Mongoose,Mongoose Schema,我有两种猫鼬模式,如下所示: 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: Stri
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);
如果我在使用“选定”配方的函数中工作,如何在数据架构中只匹配具有数据数组中的_id的数据。find()考虑到选定配方是“配方”,您可以这样做
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});
}
});
so的可能副本是这样的吗?:Recipe.findById(idR,函数(err,Recipe){if(err){console.log(err)}Recipe.populate('data',函数(err,Recipe){if(err){console.log(err)}}res.send({datarecipe:recipe.data}}})顺便说一句,我想你也可以写这个,recipe.findById(idR)。填充('数据')。exec(函数(err,recipe){if(err){console.log(err)}res.send({datarecipe:recipe.data})})我假设最初recipes.data有一个id数组,它出现在“data”集合的_id字段中。如果我必须删除数据集合中所选配方的数据数组中的所有数据,该怎么办?您甚至不需要为该数据填充。deleteMany({u id:{$in:recipe.data},function(err){});