我基于库中包含的 node-orm2 示例项目构建了一个 node express 应用程序。我有一个讨厌的“错误”,我的返回值看起来很乱。
一个“用户”只有一个“权限”:User.hasOne('permission', db.models.permission, {required: true, autoFetch: true});
一个“公司”有一个所有者,但这是相反的,所以一个“用户”有多个“公司”。Company.hasOne('user', db.models.user, { required: true, reverse: 'companies', autoFetch: true});
第一个设置:
function setup(db, cb) {
require('./company')(orm, db);
require('./user')(orm, db);
require('./permission')(orm, db);
return cb(null, db);
}
乱七八糟的结果:
{
"id": 1,
"username": "l.vanbuiten",
"name": "Lex",
"surname": "van Buiten",
"age": "1992-05-13T22:00:00.000Z",
"createdAt": "2015-12-21T23:25:04.000Z",
"permission": {
"id": 1,
"username": "l.vanbuiten",
"name": "Lex",
"surname": "van Buiten",
"age": "1992-05-13T22:00:00.000Z",
"createdAt": "2015-12-21T23:25:04.000Z",
"permission_id": 1
},
"companies": []
}
交换这些设置行后,事情得到了我想要的:
应该如何:
function setup(db, cb) {
require('./permission')(orm, db);
require('./user')(orm, db);
require('./company')(orm, db);
return cb(null, db);
}
期望的结果
{
"id": 1,
"username": "l.vanbuiten",
"name": "Lex",
"surname": "van Buiten",
"age": "1992-05-13T22:00:00.000Z",
"createdAt": "2015-12-21T23:25:04.000Z",
"permission": {
"id": 1,
"name": "permission name"
},
"companies": [
{
"id": 1,
"name": "company name",
"description": "company description",
"createdAt": "2015-12-21T23:25:25.000Z"
}
]
}
一个示例模型:
var moment = require('moment');
module.exports = function (orm, db) {
var Company = db.define('company', {
id: {type: 'serial', key: true},
name: {type: 'text', required: true, unique: true},
description: {type: 'text', big: true},
createdAt: {type: 'date', required: true, time: true}
},
{
cache: false,
hooks: {
beforeValidation: function () {
this.createdAt = new Date();
}
},
validations: {
name: [
orm.enforce.unique("Company already exist"),
orm.enforce.ranges.length(1, undefined, "Company name cannot be empty"),
orm.enforce.ranges.length(undefined, 50, "Company name is to long")
]
},
methods: {
serialize: function () {
return {
id: this.id,
name: this.name,
description: this.description,
createdAt: this.createdAt
}
}
}
});
Company.hasOne('user', db.models.user, { required: true, reverse: 'companies', autoFetch: true});
};
顺序怎么相差这么大?