Reputation: 2544
I have a sample node.js project with 2 files where i would like to store a Post-object into my database. Here is my Schema (in ./schema/post.js)
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
module.exports = function() {
var Post = new Schema({
title: String,
body: String,
date: Date
});
mongoose.model('Post', Post);
};
In the second file is the database logic (connect, save a new post-object and disconnect)
var mongoose = require('mongoose'),
Post = require('./schema/post.js');
mongoose.connect('mongodb://Thomas-PC/test');
var post = new Post();
post.title = 'asdfafsd';
post.body = 'asdfasdf';
post.date = Date.now();
post.save(function (err) {
if (err) { throw err; }
console.log('saved');
mongoose.disconnect();
});
This is not working. My question is: How can i create a new Instance of a Model-Object in the separated file?
Upvotes: 0
Views: 1179
Reputation: 1185
This can't work. You can have it working this way :
module.exports = function() {
var Post = new Schema({
title: String,
body: String,
date: Date
});
return mongoose.model('Post', Post);
}
And :
Post = require('./schema/post.js')()
Upvotes: 2