月盾的博客

sequelize.js不能将驼峰camelCased命名转化为下划线underscored命名

月盾

定义Model的时候有这样两个参数: underscored,underscoredAll,

Converts all camelCased columns to underscored if true. Will not affect timestamp fields named explicitly by model options and will not affect fields with explicitly set field option

其意思是说转化所有驼峰字段为下划线字段,但实际情况并不是如此。

var Model = sequelize.define<ModelInstance, ModelAttributes>(
    'Assistance', {
        title: Sequelize.STRING,
        description: Sequelize.STRING,
        fullName: Sequelize.STRING
    }, {
        underscored: true,
        tableName: 'assistance',
        charset: 'utf8',
        collate: 'utf8_unicode_ci'
    }
);
CREATE TABLE IF NOT EXISTS `assistance` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `description` VARCHAR(255), `fullName` VARCHAR(255), `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci;

其中fullName字段在创建表的时候还是和模型中保持一致,并没有转换为full_name,underscored的设置其实只影响到了createdAt和updatedAt等内置字段。 在github上也有相关讨论:https://github.com/sequelize/sequelize/issues/6423

Unhandled rejection CastError: Cast to ObjectId failed for value catalog at path _id for model Blog

月盾
Unhandled rejection CastError: Cast to ObjectId failed for value "catalog" at path "_id" for model "Blog"
    at MongooseError.CastError (e:\workspace\yuedun_ts\node_modules\mongoose\lib\error\cast.js:27:11)
    at ObjectId.cast (e:\workspace\yuedun_ts\node_modules\mongoose\lib\schema\objectid.js:149:13)
    at ObjectId.SchemaType._castForQuery (e:\workspace\yuedun_ts\node_modules\mongoose\lib\schematype.js:1064:15)
    at ObjectId.castForQuery (e:\workspace\yuedun_ts\node_modules\mongoose\lib\schema\objectid.js:189:15)
    at ObjectId.SchemaType.castForQueryWrapper (e:\workspace\yuedun_ts\node_modules\mongoose\lib\schematype.js:1021:15)
    at cast (e:\workspace\yuedun_ts\node_modules\mongoose\lib\cast.js:269:32)
    at Query.cast (e:\workspace\yuedun_ts\node_modules\mongoose\lib\query.js:3103:12)
    at Query._castConditions (e:\workspace\yuedun_ts\node_modules\mongoose\lib\query.js:1144:10)
    at Query._findOne (e:\workspace\yuedun_ts\node_modules\mongoose\lib\query.js:1346:8)
    at e:\workspace\yuedun_ts\node_modules\mongoose\node_modules\kareem\index.js:250:8
    at e:\workspace\yuedun_ts\node_modules\mongoose\node_modules\kareem\index.js:23:7
    at nextTickCallbackWith0Args (node.js:489:9)
    at process._tickCallback (node.js:418:13)
From previous event:
    at Query.exec (e:\workspace\yuedun_ts\node_modules\mongoose\lib\query.js:2897:17)
    at Query.then (e:\workspace\yuedun_ts\node_modules\mongoose\lib\query.js:2945:15)
    at Object.default_1 [as default] (e:\workspace\yuedun_ts\utils\viewer-log.ts:21:10)
    at e:\workspace\yuedun_ts\app.ts:53:14
    at Layer.handle [as handle_request] (e:\workspace\yuedun_ts\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:317:13)
    at e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:284:7
    at param (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:354:14)
    at param (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:365:14)
    at Function.process_params (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:410:3)
    at next (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:275:10)
    at e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:635:15
    at next (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:260:14)
    at Function.handle (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:174:3)
    at router (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (e:\workspace\yuedun_ts\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:317:13)
    at e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:335:12)
    at next (e:\workspace\yuedun_ts\node_modules\express\lib\router\index.js:275:10)
    at e:\workspace\yuedun_ts\node_modules\express-session\index.js:489:7
    at e:\workspace\yuedun_ts\node_modules\connect-mongo\lib\connect-mongo.js:305:11
    at handleCallback (e:\workspace\yuedun_ts\node_modules\mongoose\node_modules\mongodb\lib\utils.js:120:56)
    at e:\workspace\yuedun_ts\node_modules\mongoose\node_modules\mongodb\lib\collection.js:1417:5
    at handleCallback (e:\workspace\yuedun_ts\node_modules\mongoose\node_modules\mongodb\lib\utils.js:120:56)

乍看之下有用的只有第一行,意思是将catalog赋值给_id,但是这么一大片都是mongoose相关的错误,找不到在哪爆出来的错误,再仔细看一下,其实还是指出了具体错误代码:

open() is deprecated in mongoose >= 4.11.0, use openUri()

月盾
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, 
or set the `useMongoClient` option if using `connect()` or `createConnection()`. 
See http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the next major 
release 3.x as MongoDB 3.6 will only allow auth against users in the admin db 
and will no longer allow multiple credentials on a socket. 
Please authenticate using MongoClient.connect with auth credentials.

修改连接参数:

url = `mongodb://${this.username}:${this.password}@${this.host}:${this.port}/${this.dbName}`;

const opts = {
	// autoReconnect: false,//默认true
	// reconnectTries: 30,//尝试重连,默认30次
	// reconnectInterval: 1000, //重连间隔,默认1000毫秒
	loggerLevel: "warn", //error/warn/info/debug
	useMongoClient: true
};
mongoose.connect(this.url, opts);

如果在原有参数的基础上加了userMongoClient以后有如下警告:

windows好用的bash工具——ConEmu

月盾

其实git-bash-for-windows这个git bash工具已经很好用了,不过对于平时需要开3-5的bash窗口的我来说就比较烦了,一直要不停的切换窗口,所以想找一款像linux terminal一样可以多开的工具,幸好有这样的工具,那就是ConEmu

使用前需要一些配置,不配置也没关系,就是使用起来不方便,我是按照的习惯完全配置成了git bash的使用方式。

第一步:

设置

第二步: 配置本地git bash地址(此步骤可适当配置

设置

第三步: 设置ConEmu启动即打开bash而非windows cmd

设置

第四步: 如果前面都没问题,可以设置自动保存打开的窗口,以便下次打开即可使用

设置

最后: 根据个人喜好修改字体等

设置

这样就可以完美使用git bash,不论是自动补全还是颜色主题都和git bash无异。

另外cmder其实也是我使用过的一个不错的工具,同时推荐试用。

Sequelize批量插入数据

月盾

sequelize提供了批量插入数据的方法:Model.bulkCreate([…object])。

User.bulkCreate([
  { username: 'barfooz', isAdmin: true },
  { username: 'foo', isAdmin: true },
  { username: 'bar', isAdmin: false }
]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...
  return User.findAll();
}).then(users => {
  console.log(users) // ... in order to get the array of user objects
})

npm ERR! Error: EPERM: operation not permitted

月盾

windows下npm install安装依赖的时候出现下面的错误:

npm ERR! Windows_NT 6.1.7601
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "yog2@1.0.0"
npm ERR! node v4.8.0
npm ERR! npm  v2.15.11
npm ERR! path C:\Users\Administrator\AppData\Roaming\npm-cache\images\3.0.0\package.tgz.1683947925
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall rename

npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\Administrator\AppData\Roaming\npm-cache\images\3.0.0\package.tgz.1683947925' -> 'C:\Users\Administrator\AppData\Roaming\npm-cache\images\3.0.0\package.tgz'
npm ERR!     at Error (native)
npm ERR!  { [Error: EPERM: operation not permitted, rename 'C:\Users\Administrator\AppData\Roaming\npm-cache\images\3.0.0\package.tgz.1683947925' -> 'C:\Users\Administrator\AppData\Roaming\npm-cache\images\3.0.0\package.tgz']
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'rename',
npm ERR!   path: 'C:\\Users\\Administrator\\AppData\\Roaming\\npm-cache\\images\\3.0.0\\package.tgz.1683947925',
npm ERR!   dest: 'C:\\Users\\Administrator\\AppData\\Roaming\\npm-cache\\images\\3.0.0\\package.tgz',
npm ERR!   parent: 'fis-spriter-csssprites' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     E:\workspace\zm-platform\npm-debug.log

解决方案:npm cache clear 详细参阅:Fixing intermittant ‘EPERM: operation not permitted’ on npm install

2017年上海办理居住证

月盾

说起居住证这东西,对于来沪务工的人平时没什么用,但是到一些关键时候却是不可缺少的,比如考驾照,子女上学,落户等。我也是来上海几年了都没办过,最近为了孩子上学做准备不得已就赶紧办了,之前之所以没办就是觉得麻烦。

办居住证麻烦的是准备材料,其实材料准备好了一小时甚至半小时就能办好。要准备的资料当中恐怕最难的就是房东方面了,如果房东OK其他倒是很简单。

房东方面

  1. 房东本人
  2. 房东身份证
  3. 房产证
  4. 房产所有人身份证
  5. 租赁合同
  6. 备案证明

按照上海市条文规定,房屋租赁备案证明是要缴纳5%的房租税的,这是要房东缴纳的,所以很多房东恐怕不太愿意,但实际上目前没有具体单位来收取这个税的,如果房东还是害怕收税那你们可以商量好另拟一份房租比较低的合同。办理居住证房东还需要准备身份证,房产证,如果房产为多人共同所有,那么就需要其他共有人的身份证,其实户口本是不行的,因为要刷身份证信息的。如果无法提供其他人身份证,那么就让其他人写一份委托书,这个委托书嘛!其实是不是真正的委托人写的无所谓。如果办事处还是不能接受,那么就让房东现场写一份承诺书,大概内容就是说房东可以全权代理其他人来出租这一套房产,保证今后不会产生分歧,如有分歧可以承担一切责任。其实就是保证这套房子不是由房东私自出租就行。有些房子是由二房东来出租的,没有房产证,这种情况可以先去街道办事处问一下。房东准备这些东西其实就是为了办理房屋租赁备案证明。

自己方面

  1. 身份证,2份复印件
  2. 租赁合同
  3. 劳动合同 1份复印件
  4. 近6个月社保单

在办理之前需要做一些准备,先去居委问一下街道办事处地址,也可以自己网上查,别去错地方,比如我住的地方近处就有一个街道办,但并不属于这个街道办事处管理。然后关心的可能是再哪办房屋租赁备案证明,我所在的甘泉街道办事处就是在一块的,我想其他地方也是一样的,要不然去两个地方跑就太不方便了。

go语言实现继承,重写

月盾

以实际遇到过得情况为例,用户的数据结构中有类型为日期类型time.Time的createdAt属性,经过反复的格式化处理,在页面上输出的还是2017-05-31 06:49:09 +0800 CST这种格式,所以猜想日期类型是不能直接输出2017-05-31 06:49:09格式的,只能输出格式化后的字符串类型。于是利用go的继承将User的数据结构继承都UserPojo里,再单独对createdAt进行修改,重写为string类型。

package main

import "fmt"
import "time"

type User struct {
    name string
    age int
    createdAt time.Time
}

type UserPojo struct {
    User
    createdAt string
}

func (user *User) getName(){
    fmt.Println("获取用户名:", user.name)
}

func main()  {
    user := new(User)
    user.name="张三"
    user.age=26
    user.createdAt=time.Now()
    fmt.Println("user.createdAt",user.createdAt)

    userpj := new(UserPojo)
    userpj.User = *user
    userpj.createdAt = user.createdAt.Format("2006-01-02 15:04:05")
    fmt.Println("userpj.createdAt",userpj.createdAt)
}

//输出
//user.createdAt 2017-06-17 10:39:29.5294 +0800 CST
//userpj.createdAt 2017-06-17 10:39:29

在go的继承中有一点需要注意,使用结构体struct字面量赋值会出现找不到属性的问题:

https://hopefully-img.yuedun.wang/go_extends_20180328182436.pn

# command-line-arguments
.\test.go:17:7: unknown field 'Name' in struct literal of type Cat
.\test.go:18:8: unknown field 'Color' in struct literal of type Cat

换一种方式还是有问题:

mongoose自动添加createdAt和updatedAt

月盾
export var CommentSchema: Schema = new Schema({
    Id: String,
    content: String,
    status: {
        type: Boolean,
        default: true
    }
}, { timestamps: true});

添加{ timestamps: true}选项即可,如果需要自定义属性名称可以直接指定: { timestamps: {createdAt:'created_at', updatedAt:'updated_at'}}

基于beego框架的go项目目录结构

月盾

原生的go推荐目录是

├─bin
├─pkg
├─src

bin目录放二进制文件,可以是编译后的可执行文件,也可以是安装的第三方命令行,比如beego的命令行工具会安装在bin目录。pkg存放第三方依赖,src存放代码文件。单个项目没什么疑问,就这么存放,主要是有多个项目的时候对新手来说会有点迷糊,就像我,建立了两个项目就像进了迷宫,提交到git上就更乱了,究其原因是把bin目录和pkg目录当做项目源码的一部分了。其实这两个目录是作为公共目录存在的,多个项目公用。src目录下也是可以有多个项目的,每个项目有自己独立的文件夹。

.src\
├─project1
├─project2
├─project3

所以在创建项目和克隆代码时都是在src目录下进行,不能把bin目录和pkg目录提交到git上。

但是beego并没有完全遵循这一原则,它将二进制文件直接编译到了项目源码目录下,或许可配置生成目录,暂时没有了解到,所以需要在.gitignore中排除掉生成的可执行文件,否则提交的时候就比较费时了。