1

nodejs中require猫鼬的最佳方法是什么?Schema

最初我在 app.js 文件中有这些,但随着模型的增多,它变得有点大而且笨拙。

现在我想将它们移动到一个models文件夹中并用于Model = require('./models/model')将它们导入 app.js

我如何获得它以Model填充实际模型?

exports = mongoose.model(...)失败并给了我一个空白对象;exports.model = mongoose.model(...)需要我执行 Model.model 才能访问它——这些都不是所需的行为)

===

编辑1

所以基本上我已经采取了

var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
  username: String,
  password: String,
  first_name: String,
  last_name: String,
  email: String
});
User = mongoose.model('User', UserSchema);

并将其放入./models/user.js

我如何得到它,使其相当于在 app.js 中拥有它?

4

1 回答 1

1

在您的 app.js 服务器文件中,包含 model.js 文件,如下所示:

var Model = require('./models/model');  //whatever you want to call it

然后,您可以像这样在服务器文件中实例化它:

//Initiate the  Business API endpoints
var model = new Model(mq, siteConf);
model.getUser(id, function() {
    // handle result
});

----

然后在你的文件中你放置在models名为 model.js 的文件夹中(或任何你想要的)你可以像这样设置它:

var mongoose = require('mongoose'); 

//MongoDB schemas
var Schema = mongoose.Schema;

var User = new Schema({
  username: String,
  password: String,
  first_name: String,
  last_name: String,
  email: String
});
var UserModel = mongoose.model('User', User);

// your other objects defined ...


module.exports = function(mq, siteConf) {
//MongoDB
mongoose.connect(siteConf.mongoDbUrl);


// ------------------------
// READ API
// ------------------------

// Returns a user by ID
function getUser(id, found) {
    console.log("find user by id: " + id);
    UserModel.findById(id, found);
}

// Returns one user matching the given criteria
// mainly used to match against email/login during login
function getUserByCriteria(criteria, found) {
    console.log("find user by criteria: " + JSON.stringify(criteria));
    UserModel.findOne(criteria, found);
}



    // more functions for your app ...



return {
    'getUser': getUser, 
            'getUserByCriteria': getUserByCriteria
   };
};
于 2012-07-27T04:09:21.403 回答