【问题标题】:How to find documents by Id from an Array of IDs taken from another schema?如何从另一个模式中获取的 ID 数组中按 ID 查找文档?
【发布时间】:2019-06-24 23:47:06
【问题描述】:

我有 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 的数据?

【问题讨论】:

标签: node.js express vue.js mongoose mongoose-schema


【解决方案1】:

考虑到选择的菜谱是'recipe',你可以这样做,

recipe.populate('data', function (err, recipe) {
    // here recipe.data will have the array of data objects instead of just _ids
  });

如果所选配方是精益或不是猫鼬文档,这将不起作用

【讨论】:

  • 这样对吗?:Recipe.findById(idR, function (err, recipe){ if (err) { console.log(err) } recipe.populate('data', function (err , recipe){ if (err) { console.log(err) } res.send({ datarecipe: recipe.data }) }) })
  • 顺便说一句,我认为你也可以写这个,Recipe.findById(idR)。填充(“数据”)。 exec(function (err, recipe) { if (err) { console.log(err) } res.send({ datarecipe: recipe.data }) })
  • 我假设最初 recipes.data 有一个 id 数组,它们存在于“数据”集合的 _id 字段中。
  • 如果我必须删除所选配方的数据数组中的数据集合中的所有数据怎么办?
  • 你甚至不需要填充那个 Data.deleteMany({ _id: { $in: recipe.data } }, function (err) {});
【解决方案2】:

修正字段类型:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2018-08-19
    相关资源
    最近更新 更多