“Mongoose virtual populate” Kode Jawaban

Mongoose Virtual Populate Tidak Bekerja

// virtual pupulate
AuthorSchema.virtual('posts', {
  ref: 'BlogPost',
  localField: '_id',
  foreignField: 'author'
})

// add this in your schema if vritual is not work, this method working for me
AuthorSchema.set('toObject', { virtuals: true })
AuthorSchema.set('toJSON', { virtuals: true })
Restu Wahyu Saputra

Mongoos mengisi referensi

const storySchema = Schema({
  authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
  title: String
});

// Later

const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors; // `[]`
Strange Squirrel

Mongoose virtual populate

// Specifying a virtual with a `ref` property is how you enable virtual
// population
AuthorSchema.virtual('posts', {
  ref: 'BlogPost',
  localField: '_id',
  foreignField: 'author'
});

const Author = mongoose.model('Author', AuthorSchema, 'Author');
const BlogPost = mongoose.model('BlogPost', BlogPostSchema, 'BlogPost');
Selfish Skipper

Referensi Mongoose Model Lain

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var eventSchema = Schema({
    title     : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});

var personSchema = Schema({
    firstname: String,
    lastname: String,
    email: String,
    gender: {type: String, enum: ["Male", "Female"]}
    dob: Date,
    city: String,
    interests: [interestsSchema],
    eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});

var Event  = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
our Supreme Lord and Savior

Jawaban yang mirip dengan “Mongoose virtual populate”

Pertanyaan yang mirip dengan “Mongoose virtual populate”

Lebih banyak jawaban terkait untuk “Mongoose virtual populate” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya