我正在尝试创建一个带有 Node 的模型,并且我希望能够像这样使用它:
需要模型
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();
});
使用示例
我希望能够使用这样的模型创建、查找(一个或多个)、更新和删除 token (例如)。例如,我将在 Controller 或库上使用它。
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 :
我尝试使用 Backbone,新的 Token({/* attribute */}) 可以工作,但 find 函数返回错误: TypeError: Object function (){ returnparent.apply(this,arguments); } 没有“查找”方法
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, []);
}
};
创建模型来处理 Controller 上的所有对象的最佳方法是什么?
感谢您的帮助!
最佳答案
给你:
YourModule = function(data){
this.data = data; // this.data is now a property of the object you create with New.
};
YourModule.prototype.find = function(query, callback) {
console.log("[Step] models/token.js - find");
console.log(" query : ", query);
callback(null, []);
return this.data; // this.data is available here.
};
YourModule.prototype.save = function(data) {
this.data = data; // this.data is available here to.
};
module.exports = YourModule;
您无法使用 new 关键字实例化对象,但是可以执行 Object.create
来执行此操作。不过我更喜欢我的例子。
关于javascript - 使用允许新模型和 Model.find() 的 Node 创建我自己的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648517/