Mongoose 'populate' not populating

泄露秘密 提交于 2019-12-25 05:25:34

问题


I am building a fairly simple application on the MEAN stack and I am really out of my depth, especially when it comes to mongoose. I have found the mongoose documentation very difficult to wrap my head around and cannot find answers anywhere else.

My issue is this: I have a bunch of users, these users have repositories and the repositories have repository providers (GitHub, BitBucket etc).

A user has many repositories and a repository has one repository type.

My user file contains the following:

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

var UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    repositories: [{
        name: String,
        branches: [{
            name: String,
            head: Boolean,
            commits: [{
                hash: String,
                date: Date,
                message: String,
                contributer: String,
                avatar: String
            }]
        }],
        repoType: { 
            type: Schema.Types.ObjectId, 
            ref: 'RepoProviders'
        }
    }]
});

var User = mongoose.model('User', UserSchema);

module.exports = User;

// This is where the magic doesn't happen :(

User.find({ name: "John Smith"}).populate({path: 'repoType'}).exec(function (err, user) {
  if (err) return handleError(err);
  console.log(user);
});

RepoProvider.js contains:

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

var RepoProviderSchema = new Schema({
    name: {
        type: String,
        required: true
    }
});

var RepoProvider = mongoose.model('RepoProviders', RepoProviderSchema);
module.exports = RepoProvider;

I am creating user documents in mongo and manually assigning a repoType id hash (taken from an existing repoType document).

When I console.log the User, the repo type is set to the id but there is no relationship returned:

[ { _id: 5547433d322e0296a3c53a16,
    email: 'john@smith.com',
    name: 'John Smith',
    __v: 0,
    repositories: 
     [ { name: 'RepoOne',
         repoType: 5547220cdd7eeb928659f3b8,
         _id: 5547433d322e0296a3c53a17,
         branches: [Object] } ] } ]

How do I properly set and query this relationship?


回答1:


You need to specify the full path to repoType in the populate method:

User.find({ name: "John Smith"}).populate({path: 'repositories.repoType'}).exec(function (err, user) {
  if (err) return handleError(err);
  console.log(user);
});


来源:https://stackoverflow.com/questions/30027477/mongoose-populate-not-populating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!