Reputation: 13492
I am using mongoose with node.js, I have a file called models.js where I define my schema then export them.
module.exports = {
Team : mongoose.model('Team', Team),
Player : mongoose.model('Player', Player)
};
When I want to query the DB I run commands like
models.Team.find({}, function(err, teams) {
console.log(teams); // this lists all the teams just fine, function works
});
But I am trying to create a new collection so I can save my Players collection into a new one then clear the collection. So I am trying the below and I get has no method 'createCollection'
models.Player.createCollection('week1');
I have also tried the below, not really sure how to define my target lol but I have used robo mongo to create a collection called test
models.Player.copyTo('test')
Upvotes: 0
Views: 823
Reputation: 86
One way to do this is like this:
Make a method that takes as arguments the collection's name and the collection's model, and returns the mongoose model that corresponds to the given collection name and model. for example:
function createCollection (collectionName, model) {
return mongoose.model(collectionName, model);
}
Then you could use the createCollection
function to get seperate collections using the same schema. For example:
Considering that you have defined the Player's schema like this:
var playerSchema = {
name: String
};
You could get a collection for week 1 players, and a separate collection for week 2 players like this ( you could extend it to as many collections you want, or to collections for fixed time periods i.e. weekly etc, according to your needs ):
var Player_week_1 = createCollection('week_1_player', playerSchema);
var Player_week_2 = createCollection('week_2_player', playerSchema);
To summarize, the following working code shows how it can be done:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
function createCollection (collectionName, model) {
return mongoose.model(collectionName, model);
}
var playerSchema = {
name: String
};
var Player_week_1 = createCollection('week_1_player', playerSchema);
var Player_week_2 = createCollection('week_2_player', playerSchema);
var playerA = new Player_week_1( { name: 'playerA-week-1'});
playerA.save(function (error) {
if (error) {
console.log('error saving playerA in week_1_players');
} else {
console.log('saved playerA in week_1_players');
}
});
var playerB = new Player_week_2( { name: 'playerB-week-2'});
playerB.save(function (error) {
if (error) {
console.log('error saving playerB in week_2_players');
} else {
console.log('saved playerB in week_2_players');
}
});
Upvotes: 0
Reputation: 4373
With Mongoose, the model is the name of the collection. You can override it, but are you sure you want a different collection for each week? Mongo collections are similar to tables in the rdbms world. You probably would not want a new table for each week.
Upvotes: 2