MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

mangouste :remplir dans la mangouste qui n'a pas d'ObjectId

Vous pouvez utiliser le concept de Virtuals . Voici comment ça se passe :

Modifiez votre fichier de schéma comme suit :

//---------------------------------------------------
const gameSchema = new mongoose.Schema({
  title: String,
  rating: { type: Number, min: 0, max: 100 },
  genres: [Number],//here you have an array of id of type Number as yours, no ref
});
const GenreSchema = new mongoose.Schema({
  id: { type: Number },
  name: String,
  description: String,
});

gameSchema.virtual("games", {
  ref: "Genres",//this is the model to populate
  localField: "id",//the field used to make the populate, it is the field that must match on the aimed  Genres model <- here is the trick you want!!!  
  foreignField: "genres",//the field to populate on Games model
  justOne: false,
});

 gameSchema.set("toObject", { virtuals: true });//if you are planning to use say console.log
 gameSchema.set("toJSON", { virtuals: true });//if you are planning to use say res.json

mongoose.model("Games", gameSchema);
mongoose.model("Genres", GenreSchema);
//-------------------------------------------------

Dans le fichier que vous essayez de remplir, mettez ceci dans la section déclaration :

//-----------------------------------------------------
const Games = mongoose.model("Games", gameSchema);
//---------------------------------------------------

Enfin et surtout, où vous souhaitez remplir :

//----------------------------------------------
Games.find({})
  .populate("games")
  .exec(function (error, games) {
   //with games you can use things like game.field1, it is actually an JSON object! Print out games and see the fieds for your self, select one and call it using the dot notation! 
    console.log(games);
  });
//---------------------------------------------

J'ai testé cette solution sur un problème que j'avais fait, juste modifié pour répondre à vos besoins, s'il vous plaît, faites-moi savoir si cela fonctionne chez vous; sinon, nous pouvons trouver ensemble comment adapter ma solution à vos besoins.

Quelques premières références

  1. Remplir un modèle de mangouste avec un champ qui n'est pas un identifiant