简体   繁体   中英

Node.js + Mongoose: Model / Schema separated from db logic

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?

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')()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM