简体   繁体   English

Node.js + Mongoose:模型/模式与db逻辑分离

[英]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. 我有一个示例node.js项目,包含2个文件,我想将Post-object存储到我的数据库中。 Here is my Schema (in ./schema/post.js) 这是我的架构(在./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) 第二个文件中是数据库逻辑(连接,保存新的post-object并断开连接)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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