MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

mangusta:popola in mangusta che non ha alcun ObjectId

Puoi usare il concetto di Virtuals . Ecco come va:

Modifica il file dello schema come segue:

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

Sul file che stai tentando di popolare, inserisci questo nella sezione di dichiarazione:

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

Ultimo ma non meno importante, dove vuoi popolare:

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

Ho testato questa soluzione su un problema che avevo fatto, appena modificato per soddisfare le tue esigenze, per favore, fammi sapere se funziona nel tuo; in caso contrario, possiamo capire insieme come adattare la mia soluzione alle tue esigenze.

Alcuni riferimenti iniziali

  1. Popolare un modello di mangusta con un campo che non è un ID