Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何从另一个模式的Id数组中按Id查找文档?_Node.js_Express_Vue.js_Mongoose_Mongoose Schema - Fatal编程技术网

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){});