MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mungo:Füllen Sie Mungo aus, das keine ObjectId hat

Sie können das Konzept von Virtuals verwenden . So geht's:

Ändern Sie Ihre Schemadatei wie folgt:

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

Fügen Sie in der Datei, die Sie zu füllen versuchen, Folgendes in den Deklarationsabschnitt ein:

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

Zu guter Letzt, wo Sie füllen möchten:

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

Ich habe diese Lösung an einem Problem getestet, das ich gemacht hatte, nur an Ihre Bedürfnisse angepasst. Bitte lassen Sie mich wissen, ob es bei Ihnen funktioniert. Wenn nicht, können wir gemeinsam herausfinden, wie ich meine Lösung an Ihre Bedürfnisse anpassen kann.

Einige erste Referenzen

  1. Füllen Sie ein Mungo-Modell mit einem Feld, das keine ID ist