Reputation: 27
I using mongoose with express.js
I designed server is create model dynamically.
var schema = mongoose.Schema({ data: String }, { timestamps: true });
var model = mongoose.model(result.siteId, schema);
var data = new model({
data: JSON.stringify(req.body)
});
data.save(function (err, result) {
if (err) {
res.status(400).json({
success: false
});
} else {
res.status(200).json({
success: true,
data: result
});
}
});
this is this part of create models. (data input part) Once server get request, request's siteId is model's name. It is properly works. but problem is using this created model. I want this mongodb table. So i redeclare models but it not works.
var datas = mongoose.model('modelname', {data: String});
Once declare this model. 'data input part' (upper code) is not working and stopped server response and timeout message. but other 'data input part' using another modelname is working.
i think mongoose stopped from redeclare model. I want declare models other js file and use. but modelsname is must dynamic name.
What is proper way?
Upvotes: 0
Views: 759
Reputation: 18225
Had a similar problem trying to reuse Schema
s with different names and only managed to get it working by providing the collection name to Schema
creation as well.
You can accomplish something similar by adding the collection
param to your Schema creation options.
But then you need different Schema
objects for each model
, so I suggest creating a function to retrieve models, based on a collection name, like
var buildModel = function(collectionName) {
var schema = mongoose.Schema({ data: String }, { timestamps: true, collection: collectionName });
return mongoose.model(collectionName, schema);
}
var model = buildModel(result.siteId);
var data = new model({
...
Upvotes: 1