Reputation: 145
I am trying to use Mongoose JS to come up with a design for my database with the following structure. Each user will own an array of tournaments. My problem is that the database will store everything except the array of TournamentSchemas on saving. It's just an empty array. I'm not sure what I'm doing wrong here, and I've looked elsewhere on this site.
Here is what I'm trying to make my db look like:
User {
name : String
email : String
password : String
tournaments : [
{
name : String
location : String
date : ISO_DATE
numTeams : NumberInt
Here's user.js:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Tournament = mongoose.model("Tournament");
var TournamentSchema = require("./tournament").TournamentSchema;
var UserSchema = new Schema({
name : String,
email : String,
password : String,
tournaments : [TournamentSchema]
});
mongoose.model("User", UserSchema);
And here's tournament.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var TournamentSchema = new Schema({
name : String,
location : String
});
mongoose.model("Tournament", TournamentSchema);
module.exports = TournamentSchema;
And here's how I'm instantiating a new User in my controller class:
var user = new User({
name : name,
email : email,
password : password,
tournaments : [
{
name : "Trial by Combat",
location : "King's Landing"
}
]
});
I'm not entirely sure if the way I have the line "tournaments : [TournamentScheme]" is the correct way to say that that variable will be an array of TournamentSchemes. If anyone has a solution, I'd greatly appreciate if you could also walk me through what I'm doing wrong.
Upvotes: 2
Views: 2397
Reputation: 145
I figured out the problem! For anyone who might be having the same issue:
This line in users.js
var TournamentSchema = require("./tournament").TournamentSchema;
was returning undefined because I wrote the module.exports line in tournament.js incorrectly. To fix it, I changed the last two lines in tournament.js to a single line:
module.exports = mongoose.model("Tournament", TournamentSchema);
That line will correctly export the model object so that it's schema can be gotten from users.js. Then, I changed the aforementioned line in user.js to:
var tournamentSchema = require("./tournament").schema;
To test it, I instantiated a new Tournament in my controller class and then pushed it to the tournaments array:
var t = new Tournament({
name : "Trial by Combat",
location : "King's Landing"
});
var user = new User({
name : name,
email : email,
password : password,
});
user.tournaments.push(t);
// Save to db down here....
The database is updated correctly!
Upvotes: 4