2015-03-13 2 views
0

Привет Я новичок в мангустов и у меня есть проблемы с коллекции заселить не возвращает никаких данных, я не знаю, почему вот мой код:Mongoosejs: Populate не возвращает никаких данных

Компания Модель

'use strict'; 

/** 
* Module dependencies. 
*/ 
var mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    Agent = mongoose.model('Agent'), 
    DBRef = mongoose.SchemaTypes.DBRef; 

/** 
* Company Schema 
*/ 
var CompanySchema = new Schema({ 
name: { 
    type: String, 
    default: '', 
    //required: 'Please fill Company name', 
    trim: true 
}, 
created: { 
    type: Date, 
    default: Date.now 
}, 
updated: { 
    type: Date, 
    default: Date.now 
}, 
address: { 
    type: String, 
    default: '', 
    //required: 'Please fill Company address', 
    trim: true 
}, 
locked: { 
    type: Boolean, 
    default: true, 
}, 
deleted: { 
    type: Boolean, 
    default: false, 
}, 
logo: { 
    type: String, 
    default: '', 
}, 
email: { 
    type: String, 
    default: '', 
    index: { unique: true } 
    //required: 'Please fill Company email', 
}, 
tel: { 
    type: String, 
    default: '', 
    //required: 'Please fill Company tel', 
}, 
fax: { 
    type: String, 
    default: '', 
    //required: 'Please fill Company fax', 
}, 
type: { 
    type: String, 
    //required: 'Please fill Company type', 
    trim: true 
}, 
description: { 
    type: String, 
    default: '', 
    trim: true 
}, 
validator: { 
    type: Schema.ObjectId, 
    ref: 'User' 
}, 
admins: [Agent] 
}); 

module.exports = mongoose.model('Company', CompanySchema); 

Агент Модель

'use strict'; 

/** 
* Module dependencies. 
*/ 
var mongoose = require('mongoose'), 
Schema = mongoose.Schema, 
//Company = mongoose.model('Company'), 
DBRef = mongoose.SchemaTypes.DBRef; 

/** 
* Agent Schema 
*/ 
var AgentSchema = new Schema({ 
// Agent model fields 
// ... 
firstname: { 
    type: String, 
    default: '' 
}, 
lastname: { 
    type: String, 
    default: '' 
}, 
email: { 
    type: String, 
    default: '', 
    index: { unique: true } 
}, 
password: { 
    type: String, 
    default: '' 
}, 
roles: { 
    type: Array, 
}, 
created: { 
    type: Date, 
    default: Date.now 
}, 
updated: { 
    type: Date, 
    default: Date.now 
}, 
deleted: { 
    type: Boolean, 
    default: false 
}, 
locked: { 
    type: Boolean, 
    default: false 
}, 
workFor: { 
    type: Schema.ObjectId, 
    ref: 'Company' 
} 
}); 

module.exports = mongoose.model('Agent', AgentSchema); 

Populate Код

Company.findById(id).populate('admins').exec(function(err, company) { 
    if (err) return next(err); 
    if (!company) return next(new Error('Failed to load Company ' + id)); 
    console.log(company.admins); 
    req.company = company ; 
    next(); 
}); 

спасибо :).

ответ

0

Ваше определение схемы компании фактически определяет, что агенты встроены в документ компании, а не ссылки. Если вы хотите ссылки, которые вы затем могли заселить вы должны использовать что-то вроде этого:

var CompanySchema = new Schema({ 
.... 
admins: [{type: Schema.Types.ObjectId, ref: 'Agent'}], 
.... 
+0

я сделать это, но это не дает какой-либо reslut – fynx

+0

ну, ваша схема и ваш запрос выглядят правильно (если вы сделали исправление, которое я предложил в ответе выше). Может быть, в вашей базе данных у вас нет объектов компании, содержащих ObjectIds администраторов в коллекции company.admins? вы проверили содержимое своей БД на этот запрос? или покажите нам код, в котором вы сохраняете объекты компании и связанные объекты администрирования. – Reto

+0

thnks, вот мой код ниже – fynx

0

Thnks Reto, здесь экономия код компании:

/** 
* Create a Company 
*/ 
exports.create = function(req, res) { 
    var company = new Company(req.body); 
    User.findById('54e22d19aae0cff01a47df96',function(err,user){ 
     if (err) { 
      return res.status(400).send({ 
       messages: errorHandler.getErrorMessage(err) 
      }); 
     } 


     company.user = user; 
     req.checkBody('name', 'please fill the name').notEmpty(); 
     req.checkBody('address', 'please fill the address').notEmpty(); 
     req.checkBody('tel', 'please fill a correct phone').notEmpty().isNumeric(); 
     req.checkBody('type', 'please fill the type').notEmpty(); 
     req.checkBody('email', 'please fill a correct email').isEmail(); 
     req.checkBody('admin.firstname', 'please fill the admin firstname').notEmpty(); 
     req.checkBody('admin.lastname', 'please fill the admin lastname').notEmpty(); 
     req.checkBody('admin.email', 'please fill a correct admin email').isEmail(); 
     req.checkBody('admin.password', 'please fill the admin password').notEmpty(); 

     var errors = req.validationErrors(); 

     if (errors) { 
      return res.status(400).send({ 
        messages: errors 
       }); 
     }else{ 


      company.save(function(err) { 
       if (err) { 
        return res.status(400).send({ 
         messages: errorHandler.getErrorMessage(err) 
        }); 
       } else { 
        var agents = preapareAgents(req,company); 
        Agent.create(agents,function(err){ 
         if(err){ 
          return res.status(400).send({ 
           messages: errorHandler.getErrorMessage(err) 
          }); 
         }else{ 
          res.jsonp({company: company, agents: agents}); 
         } 
       }); 

       } 
      }); 

     } 
    }); 


}; 
+0

Вы смешиваете две разные концепции: 1. Вложенный документ, в котором администраторы являются частью схемы компании (и резервируются в каждой компании) и 2. Ссылки, в которых администраторы сохраняются в другой коллекции и вы сохраняете только ссылки в объектах компании. Только во втором случае вам нужно заполнить. Ваша первоначальная схема и ваш код сохранения предполагают концепцию 1, ваш код запроса с заполнением предполагает концепцию 2. Оба они в порядке, вам просто нужно решить, какой из них использовать. – Reto

+0

На самом деле, я снова посмотрел на ваш код. Я не уверен в ваших намерениях, ваш код экономии предполагает, что на компанию есть 1 агент, но ваша схема имеет массив. Должен ли этот вызов сохранить новую компанию И нового агента? Если вам нужны ссылки только в корпоративной схеме, вам сначала нужно сохранить агента, а затем заменить свойство company.agents массивом, содержащим _id уже сохраненного агента, прежде чем вы сохраните компанию – Reto

+0

это моя модель: одна компания есть несколько агентов, и агент связывается с одной компанией, как я могу представить это в мангусте, thnks. NB: Я хочу хранить администратор в альтернативной схеме. – fynx

Смежные вопросы