我通过Ruby宝石“续集”使用PostgreSQL。

我要四舍五入到小数点后两位。

这是我的代码:

SELECT ROUND(AVG(some_column),2)    
FROM table

我得到以下错误:

PG::Error: ERROR:  function round(double precision, integer) does 
not exist (Sequel::DatabaseError)

当我运行以下代码时,我没有得到错误:

SELECT ROUND(AVG(some_column))
FROM table

有人知道我哪里做错了吗?

我想从第一个中间件传递一些变量到另一个中间件,我试着这样做,但有“req。有些变量是一个给定的‘未定义’”。


//app.js
..
app.get('/someurl/', middleware1, middleware2)
...

////middleware1
...
some conditions
...
res.somevariable = variable1;
next();
...

////middleware2
...
some conditions
...
variable = req.somevariable;
...

在新版本的express上有一些中间件的变化,我也在我的代码中做了一些关于这个问题的其他帖子的更改,但我不能得到任何坚持。

我们之前让它工作,但我不记得是什么变化了。

throw new TypeError('Router.use() requires middleware function but got a
        ^
TypeError: Router.use() requires middleware function but got a Object

node ./bin/www

js-bson: Failed to load c++ bson extension, using pure JS version
js-bson: Failed to load c++ bson extension, using pure JS version

/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438
      throw new TypeError('Router.use() requires middleware function but got a
            ^
TypeError: Router.use() requires middleware function but got a Object
    at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438:13
    at Array.forEach (native)
    at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:436:13)
    at /Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:188:21
    at Array.forEach (native)
    at Function.use (/Users/datis/Documents/bb-dashboard/node_modules/express/lib/application.js:185:7)
    at Object.<anonymous> (/Users/datis/Documents/bb-dashboard/app.js:46:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var routes = require('./routes/index');
var users = require('./routes/users');

var Users = require('./models/user');
var Items = require('./models/item');
var Store = require('./models/store');
var StoreItem = require('./models/storeitem');

var app = express();
//set mongo db connection
var db = mongoose.connection; 

MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});
// var MONGOHQ_URL="mongodb://localhost:27017/test" 

// view engine setup
app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: 'something',
    resave: true,
    saveUninitialized: true
}));

app.use('/', routes);
app.use('/users', users);
app.use(express.static(path.join(__dirname, 'public')));

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//     var err = new Error('Not Found');
//     err.status = 404;
//     next(err);
// });

// Make our db accessible to our router
app.use(function(req, res, next){
  req.db = db;
  next();
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

由于版本的原因,这个问题的答案似乎已经改变了。感谢尼克

我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。

我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):

app.use((req, res, next) => {
    req.property = setProperty(); 
    next();
});

在我问app.router之前,我想我至少应该解释一下我认为在使用中间件时会发生什么。要使用中间件,需要使用的函数是app.use()。当中间件正在执行时,它将使用next()调用下一个中间件,或者使它不再调用更多的中间件。这意味着我放置中间件调用的顺序很重要,因为一些中间件依赖于其他中间件,而靠近末尾的一些中间件甚至可能不被调用。

Today I was working on my application and had my server running in the background. I wanted to make some changes and refresh my page and see the changes immediately. Specifically, I was making changes to my layout. I couldn't get it to work so I searched Stack Overflow for the answer and found this question. It says to make sure that express.static() is beneath require('stylus'). But when I was looking at that OP's code, I saw that he had his app.router call at the very end of his middleware calls, and I tried to figure out why that was.

当我做我的express. js应用程序(3.0.0rc4版),我使用命令express app -sessions -css stylus和在我的app.js文件的代码来设置与我的app.router以上的express.static()和要求('stylus')调用。所以看起来,如果它已经这样设置了,那么它应该保持这样。

在重新安排我的代码,这样我就可以看到我的手写笔的变化,它看起来像这样:

app.configure(function(){
  //app.set() calls
  //app.use() calls
  //...
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(__dirname + '/public', {maxAge: 31557600000}));
});

app.get('/', routes.index);

app.get('/test', function(req, res){
  res.send('Test');
});

So I decided that the first step would be to find out why it is important to even have app.router in my code. So I commented it out, started my app and navigated to /. It displayed my index page just fine. Hmm, maybe it worked because I was exporting the routing from my routes file (routes.index). So next I navigated to /test and it displayed Test on the screen. Haha, OK, I have no idea what app.router does. Whether it is included in my code or not, my routing is fine. So I am definitely missing something.

所以我的问题是:

谁能解释一下app.router是做什么的,它的重要性,以及我应该把它放在中间件调用的哪里?如果我能得到一个关于express.static()的简要解释,那就太好了。据我所知,express.static()是我的信息的缓存,如果应用程序找不到所请求的页面,它将检查缓存,看看它是否存在。

我已经开始使用webpack2(准确地说,v2.3.2),在重新创建我的配置后,我一直遇到一个问题,我似乎无法解决我得到(提前为丑陋的转储道歉):

ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
  Parsed request is a module
  using description file: [absolute path to my repo]/package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
      using description file: [absolute path to my repo]/package.json (relative path: ./src)
        Field 'browser' doesn't contain a valid alias configuration
      after using description file: [absolute path to my repo]/package.json (relative path: ./src)
        using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
          as directory
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          no extension
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt doesn't exist
          .js
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
          .jsx
            Field 'browser' doesn't contain a valid alias configuration
            [absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]

package.json

{
  "version": "1.0.0",
  "main": "./src/main.js",
  "scripts": {
    "build": "webpack --progress --display-error-details"
  },
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
  }
}

关于它所抱怨的浏览器字段,我能够找到的文档是:package-browser-field-spec。也有webpack文档,但它似乎默认开启:aliasFields: ["browser"]。我尝试在我的包中添加一个浏览器字段。Json,但这似乎没有任何好处。

webpack.config.js

import path from 'path';
const source = path.resolve(__dirname, 'src');

export default {
  context: __dirname,
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src/components'),
    },
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: source,
        use: {
          loader: 'babel-loader',
          query: {
            cacheDirectory: true,
          },
        },
      },
      {
        test: /\.css$/,
        include: source,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            query: {
              importLoader: 1,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
              modules: true,
            },
          },
        ],
      },
    ],
  },
};

src / main.js

import DoISuportIt from 'components/DoISuportIt';

src /组件/ DoISuportIt / index.jsx

export default function() { ... }

为完整起见,.babelrc

{
  "presets": [
    "latest",
    "react"
  ],
  "plugins": [
    "react-css-modules"
  ],
  "env": {
    "production": {
      "compact": true,
      "comments": false,
      "minified": true
    }
  },
  "sourceMaps": true
}

我做错了什么/遗漏了什么?

我有一个叫做people的mongodb集合 其架构如下:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

现在,我有一个非常基本的快速应用程序连接到数据库,并成功地创建“人”与一个空的朋友数组。

在应用程序的次要位置,有一个添加好友的表单。表单接收firstName和lastName,然后是带有名称字段的POSTs,同样用于引用适当的people对象。

我有一个困难的时间做的是创建一个新的朋友对象,然后“推”到朋友数组。

我知道当我通过mongo控制台这样做时,我使用$push作为查找标准后的第二个参数的更新函数,但我似乎找不到合适的方法让猫鼬这样做。

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

假设mongodb文档(表)“用户”是

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    birth: new Date('Dec 03, 1924'),
    death: new Date('Mar 17, 2007'),
    contribs: ['Fortran', 'ALGOL', 'Backus-Naur Form', 'FP'],
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        },
        {
            award: 'Turing Award',
            year: 1977,
            by: 'ACM'
        }
    ]
}
// ...and other object(person)s

我想找到那个必须在1975年被授予“国家勋章”的人 可能还有其他人在不同的年份获得过这个奖项。

我如何使用奖项类型和年份找到这个人。这样我就能得到准确的人。

我有一个基本的Node.js应用程序,我试图使用Express框架启动。我有一个views文件夹,其中有一个index.html文件。但是我在加载网页时收到以下错误:

Error: Cannot find module 'html'

下面是我的代码。

var express = require('express');
var app = express.createServer();

app.use(express.staticProvider(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render('index.html');
});

app.listen(8080, '127.0.0.1')

我错过了什么?

我有一个Express Node.js应用程序,但我也有一个机器学习算法在Python中使用。是否有一种方法可以从我的Node.js应用程序调用Python函数来利用机器学习库的强大功能?