Mongoose relation one-to-many not work

1,809 views
Skip to first unread message

fayssal tahtoub

unread,
Mar 12, 2015, 2:50:04 PM3/12/15
to mongoo...@googlegroups.com
I have a problem with mongoose schema relationship one-to-many: I have two documents company and agent, when I try to save the company document it cant be saved. Note: the parent document is the company and the child is the agent:
Company Model :

'use strict';

/**
* Module dependencies.
*/

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

/**
* 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: '',
   
//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
},
user
: {
       type
: Schema.ObjectId,
       
ref: 'User'
   
},
   agents
: [{
      type
: Schema.ObjectId,
     
ref: 'Agent'
   
}]
});

mongoose
.model('Company', CompanySchema);

Agent Model :
'use strict';

/**
* Module dependencies.
*/

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

/**
* Agent Schema
*/

var AgentSchema = new Schema({
// Agent model fields  
// ...
firstname
: {
    type
: String,
   
default: ''
},
lastname
: {
    type
: String,
   
default: ''
},
email
: {
    type
: String,
   
default: ''
},
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
},
company
: {
    type
: Schema.ObjectId,
   
ref: 'Company'
 
}
});

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


Save Code :


var preapareAgents = function(req,company){
var admin = new Agent(req.body.admin);
admin
.roles = ['admin', 'read','write'];
admin
.company = company;
admin
.locked = false;

var agents = req.body.agents;

for (var i = 0; i <= agents.length - 1; i++) {
    agents
[i].roles = [agents[i].role];
    agents
[i] = new Agent(agents[i]);
    agents
[i].company = company;
}

agents
.push(admin);

return agents;
};

company
.save(function(err){
 
if(err){
    console
.log('company err');
   
return res.status(400).send({
      messages
: errorHandler.getErrorMessage(err)
   
});
 
}else{
    console
.log('company save');
   
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
       
});
     
}
   
});
 
}
});

Here is the error :

CastError: Cast to ObjectId failed for value "[object Object]" at path "agents"



or how i can use mongooose-dbref plugin because i try to install and use it but it isnt work, please help me!!!!!!

fayssal tahtoub

unread,
Mar 13, 2015, 10:32:32 AM3/13/15
to mongoo...@googlegroups.com
nobody here !!!!!!

Ryan Wheale

unread,
Mar 16, 2015, 3:19:35 AM3/16/15
to mongoo...@googlegroups.com
You're not giving enough information.  At first glance thought you are nesting a "ref" type within another ref:

user: {
       type
: Schema.ObjectId,
       
ref: 'User'
   
},
   agents
: [{
      type
: Schema.ObjectId,
     
ref: 'Agent'
   
}]
}
I've never really seen this type of structure.  Instead, your "User" schema should have a property "agents" with a ref to the agents collection.

Also worth mentioning, when you have multiple collections depending on each other like this (many "joins" if you will), you might be better off using relational database technology.  That's what it's for (think stored procedures, etc - it's built for doing this type of stuff).  Trying to bend mongo into the same data structure as a relational database is not the way to think about things.  Mongo will read from one collection at a time.  Loading a company, agents, and users is three different queries... which can become a heavy operation as your collections grow and your user base grows.  Try and structure you data to reduce queries.  Duplicity is not a bad thing in mongo and it should be part of your strategy.

For example, you want to display a company and their agents.  You don't need to know everything about an agent in this situation... just their first name, last name, and agent ID.  So store their full profile in the agents collection, but also store their first, last, and ID in the company collection.  While this is duplicitous, it's unlikely that a person will update their name in the future.  Now when you go to query a company and their agents, you only need one query against the company collection.  If the end user wants more information about an agent, then you query the agents collection separately.  This is a vastly different approach than you would take with a conventional relational database.

I don't know your situation and this suggestion might not be the best for your app... but the greater point is that you need to think differently than you did in SQL land.  Don't be afraid of duplicity... try and minimize queries.  Good luck.


--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages