【发布时间】:2015-04-23 06:50:45
【问题描述】:
我正在尝试使用节点创建一个模型,我希望能够像这样使用它:
需要模型
var Example = require('./models/example');
创建新对象
模型可以使用new创建新对象
var example = new Example({ data:'example' });
查找
模型可以使用方法找到对象
Example.find({ data: 'mongoQuery' }, function(err, examples) {});
保存
该模型可以帮助找到使用方法的对象,返回对象的方法。
Example.findOne({ query: 'example' }, function(err, example) {
example.set({ data: 'another data' });
example.save();
});
使用示例
我希望能够使用这样的模型创建、查找(一个或多个)、更新和删除令牌(例如)。例如,我将在控制器或 lib 上使用它。
var Token = require('./models/token);
// Create and save a new token
var new_token = new Token({ key: 'abcdef' });
new_token.save();
// find multiple tokens, update, and save
var token = Token.find({key: 'abcderf'}, function(tokens) {
for(var i in tokens) {
tokens[i].set({key: '123456'});
tokens[i].save();
}
});
我已经尝试了很多东西,但我无法创建一个同时允许new Example 和Example.find() 的模块。
主干:
我已经尝试使用 Backbone,新的 Token({ /* attributes */ }) 工作但 find 函数返回错误:TypeError: Object function (){ return parent.apply(this, arguments); } has no method 'find'
var Token = Backbone.Model.extend({
initialize: function(attributes) {
console.log("Token create");
console.log(" attributes : ", attributes);
},
find : function(query, callback) {
console.log("Token find");
console.log(" query : ", query);
callback(null, [ /* tokens */]);
}
});
module.exports = Token;
对象
当我尝试使用一个对象时,find 函数运行良好,但我无法将它与new 一起使用,返回错误:TypeError: object is not a function
module.exports = {
find : function(query, callback) {
console.log("[Step] models/token.js - find");
console.log(" query : ", query);
callback(null, []);
}
};
创建模型来处理控制器上的所有对象的最佳方法是什么?
感谢您的帮助!
【问题讨论】:
标签: javascript node.js backbone.js model-view-controller model