-1

i have 2 mongoose Schemas like this:

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

if i am working in a function with a "selected" recipe, how can i do the Data.find() to match in the Data Schema only the Datas with the _id that i have in the data array?

William.P
  • 114
  • 9
  • Possible duplicate of [Referencing another schema in Mongoose](https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose) – num8er Jan 31 '19 at 13:54

2 Answers2

1

Considering the selected recipe is 'recipe', you can just do,

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

This won't work if the selected recipe is lean or not a mongoose document

Elvis
  • 1,103
  • 8
  • 15
  • so is this right?: 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 }) }) }) – William.P Jan 31 '19 at 14:21
  • 1
    BTW, you can also write this I think, Recipe.findById(idR). populate('data'). exec(function (err, recipe) { if (err) { console.log(err) } res.send({ datarecipe: recipe.data }) }) – Elvis Jan 31 '19 at 14:26
  • I'm assuming initially recipes.data had an array of ids which are present in the _id field of the 'data' collection. – Elvis Jan 31 '19 at 15:07
  • and what if i have to delete all datas in Data collection that are in the data array of the selected recipe? – William.P Jan 31 '19 at 15:15
  • 1
    You don't even need to populate for that Data.deleteMany({ _id: { $in: recipe.data } }, function (err) {}); – Elvis Jan 31 '19 at 15:24
0

Fix field type:

data: {
  type: [Schema.ObjectId],
  ref: 'Data',
  default: []
}

Usage:

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});
  }
});
num8er
  • 18,604
  • 3
  • 43
  • 57