sql >> Database >  >> NoSQL >> MongoDB

Vul een mangoestmodel met een veld dat geen id is

Dit wordt ondersteund sinds Mongoose 4.5 , en heet virtuele populatie .

U moet uw relaties met buitenlandse sleutels . definiëren na uw schemadefinities en voordat modellen maken , zoals dit:

// Schema definitions

BookSchema = new mongoose.Schema({
        ...,
        title: String,
        authorId: Number,
        ...
    },
    // schema options: Don't forget this option
    // if you declare foreign keys for this schema afterwards.
    {
        toObject: {virtuals:true},
        // use if your results might be retrieved as JSON
        // see http://stackoverflow.com/q/13133911/488666
        //toJSON: {virtuals:true} 
    });

PersonSchema = new mongoose.Schema({id: Number, ...});


// Foreign keys definitions

BookSchema.virtual('author', {
  ref: 'Person',
  localField: 'authorId',
  foreignField: 'id',
  justOne: true // for many-to-1 relationships
});


// Models creation

var Book = mongoose.model('Book', BookSchema);
var Person = mongoose.model('Person', PersonSchema);


// Querying

Book.find({...})
    // if you use select() be sure to include the foreign key field !
    .select({.... authorId ....}) 
    // use the 'virtual population' name
    .populate('author')
    .exec(function(err, books) {...})


  1. Hadoop MapReduce-zelfstudie voor beginners

  2. Json-bestand invoegen in mongodb

  3. Redis Verbinding via socket op Node.js

  4. Kan geen verbinding maken met MongoDB Atlas (queryTxt ETIMEOUT)