node.js - locomotivejs 和 Mongoose : passing promise variables to a controller

标签 node.js express mongoose locomotivejs

序言: 我不确定这是否是提出这个问题的最佳方式,因为我相当确定它比我提出的问题更普遍,而且可能有一个全局模式可以解决我的担忧。

目前,这是我正在使用的原始代码上下文中的问题。

给定一个 locomotivejs Controller ,我们将其称为 Contact_Controller,其一般结构如下:

'\controllers\contact_controller.js
var locomotive = require('locomotive')
    , Controller = locomotive.Controller
    , Contact = require('../models/contact')
    , sender = require('../helpers/sender')
    ;


var Contact_Controller = new Controller();

然后:

Contact_Controller.list = function() {
//Provides a list of all current (successful) contact attempts


var controller = this;

Contact.find({status: 1}, function(err, results) {
    if(err) {
        controller.redirect(controller.urlFor({controller: "dashboard", action: "error"}));
    }
    controller.contacts = results;
    controller.render();
});
};

和型号:

'/models/contact.js
var mongoose = require('mongoose')
, mongooseTypes = require('mongoose-types')
, pass = require('pwd')
, crypto = require('crypto')
, Schema = mongoose.Schema
, Email = mongoose.SchemaTypes.Email;


var ContactSchema = new Schema({
email: {type: Email, required: true},
subject: {type: String, required: true },
message: { type: String, required: true},
status: {type: Number, required: true, default: 1},
contact_time: {type: Date, default: Date.now}
});


module.exports = mongoose.model('contact', ContactSchema);

在 contact_controller 的列表操作中,我真的不想使用 controller = this; 我通常更喜欢使用 redirect = this.redirect.bind(this);样式本地化绑定(bind)来处理此类情况。

但是,如果不创建 this 的全局变量版本并进行 Promise 的回调对话,我想不出一种将结果返回到 Controller 的 this 对象的方法对此。是否有更好的方法来返回结果变量或在此上下文中公开 contact_controller 对象?

最佳答案

你是这个意思吗?

Contact.find({status: 1}, function(err, results) {
  if (err) {
    this.redirect(this.urlFor({this: "dashboard", action: "error"}));
    return; // you should return here, otherwise `render` will still be called!
  }
  this.contacts = results;
  this.render();
}.bind(this));
 ^^^^^^^^^^^ here you bind the controller object to the callback function

关于node.js - locomotivejs 和 Mongoose : passing promise variables to a controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199971/

相关文章:

javascript - 这个错误说明了什么?类型 'ParsedQs' 不可分配给类型 'string'

javascript - Mongoose 不创建 TTL 索引

ios - iOS 中的 Sailsjs 套接字

node.js - 模板/渲染 - 如何为我的 View 之一排除或指定备用layout.mustache?

javascript - 在 Sails.js 中将数据从文件传输到渲染页面

node.js - 如何在 keystone 中提供静态站点?

python - NodeJS 包类似于 pythons PIL

Node.js 指定 tls 连接超时

node.js - 在 Node.js/Waterline 中指定返回字段?

mongodb - Mongoose 鉴别器行为