在nodejs中require
mongoose Schema
的最佳方法是什么?
最初我在app.js文件中有这些内容,但是对于更多模型来说这有点大而且不实用。
现在我想将它们移到models
文件夹中并使用Model = require('./models/model')
将它们导入app.js
如何获得Model
填充实际模型?
(exports = mongoose.model(...)
失败并给我一个空白对象; exports.model = mongoose.model(...)
要求我做Model.model来访问它 - 这些都不是理想的行为)
===
EDIT1
基本上我已经采取了
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中拥有它?
答案 0 :(得分: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
});
然后在你的文件中放入名为model.js的models
文件夹(或任何你想要的),你可以这样设置:
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
};
};