使用不是id的字段填充mongoose模型

是否有可能用一个不是_id的参考模型字段填充mongoose模型…例如用户名。

所以有点像

var personSchema = Schema({ _id : Number, name : String, age : Number, stories : { type: String, field: "username", ref: 'Story' } }); 

你可以使用populate() API。 API更加灵活,您不必在Schema中指定reffield

http://mongoosejs.com/docs/api.html#document_Document-populate http://mongoosejs.com/docs/api.html#model_Model.populate

你可以混合使用find()

这是从Mongoose 4.5开始支持的,被称为虚拟人口

您必须在模式定义之后创build模型之前定义外键关系 ,如下所示:

 // Schema definitions BookSchema = new mongoose.Schema({ ..., title: String, author_id: 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: 'author_id', 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({.... author_id ....}) // use the 'virtual population' name .populate('author') .exec(function(err, books) {...}) 

看来他们强制使用_id ,也许我们可以在将来自定义它。

这是Github上的问题https://github.com/LearnBoost/mongoose/issues/2562

这是一个使用$ lookup聚合的例子,根据相应的email字段用相应的用户填充名为Invite的模型:

  Invite.aggregate( { $match: {interview: req.params.interview}}, { $lookup: {from: 'users', localField: 'email', foreignField: 'email', as: 'user'} } ).exec( function (err, invites) { if (err) { next(err); } res.json(invites); } ); 

这可能与你正在做的事很相似。