Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a mongoose model with a field that isn't an id

Is it possible to populate a mongoose model with a field of a reference model that isn't the _id ... e.g. a username.

so something like

var personSchema = Schema({   _id     : Number,   name    : String,   age     : Number,   stories : { type: String, field: "username", ref: 'Story' } }); 
like image 385
angulord Avatar asked Oct 10 '13 04:10

angulord


People also ask

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

What does populate method do Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

Does Mongoose populate use lookup?

Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.


2 Answers

This is supported since Mongoose 4.5, and is called virtuals population.

You have to define your foreign keys relationships after your schemas definitions and before creating models, like this:

// 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) {...}) 
like image 116
Frosty Z Avatar answered Sep 19 '22 12:09

Frosty Z


It seems they enforce to use _id, and maybe we can customize it in the future.

Here is the issue on Github https://github.com/LearnBoost/mongoose/issues/2562

like image 37
Leo Gao Avatar answered Sep 20 '22 12:09

Leo Gao