javascript - 使用允许新模型和 Model.find() 的 Node 创建我自己的模型

标签 javascript node.js backbone.js model-view-controller model

我正在尝试创建一个带有 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 ExampleExample.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/

相关文章:

javascript - Weebly 在我的 javascript 中在正斜杠之前插入反斜杠

javascript - 在 Node.js 中从另一个绝对路径中减去一个绝对路径

javascript - 无法理解 Node.js 中的错误

javascript - angular2,typescript peer 无效,无法导入模块

javascript - D3.js 表附加相同的数据值

javascript - 在 SVG "Path"元素/三 Angular 形的两侧生成内阴影效果

javascript - 将浏览器作为终端进程运行

javascript - 通过javascript从数字类型输入字段计算总和

javascript - 当 View 添加新的 DOM 元素时,backbone.js click 事件不会触发

javascript - 使用 Underscore.js、jQuery 和 jQueryUI 在 RequireJS 中无法正确加载 Gridstack.js