在 Sequelize 中,如果你做了
db.MyTable.findAll({}).function(response){
console.log(response);
}
您将看到如下所示的输出(当然,这取决于您的表格):
[ { dataValues:
{ id: 1,
text: 'sdf',
complete: false,
createdAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time),
updatedAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time) },
_previousDataValues:
{ id: 1,
text: 'sdf',
complete: false,
createdAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time),
updatedAt: Thu Jan 19 2017 11:55:38 GMT-0500 (Eastern Standard Time) },
_changed: {},
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: [Object],
omitNul: false,
sequelize: [Object],
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: false,
'$schema': null,
'$schemaDelimiter': '',
raw: true,
attributes: [Object] },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
可以说,它是一个巨大的复杂对象,上面有一堆元数据。
但是,如果您尝试使用以下任一方法将那个大的复杂对象转换为字符串:
console.log(JSON.stringify(dbTodo));
或
res.json(dbTodo);
您将仅返回实际实体的信息(大型复杂对象的 dataValues 属性中的项目)。对于我在这里的测试表,它看起来像这样:
[{
"id":1,
"text":"sdf",
"complete":false,
"createdAt":"2017-01-19T16:55:38.000Z",
"updatedAt":"2017-01-19T16:55:38.000Z"
}]
这要简单得多(也是我想要的)。
这个魔法是如何发生的? Sequelize 是否创建了自己版本的 JSON.stringify() 和express' res.json?
当它发生和不发生时有什么规则?
最佳答案
这种行为有两种表现形式。
缺少的属性是不可枚举的。
Object.defineProperty
定义的属性设置为enumerable: false
(或者只是不为enumerable
设置提供值)是不可枚举属性,并且会被JSON.stringify
忽略。您可以在Object.getOwnPropertyDescriptor(obj, propName)
的输出中检查属性的enumerable
设置。 .该对象具有(或在其原型(prototype)链中)一个
toJSON
method :If an object being stringified has a property named
toJSON
whose value is a function, then thetoJSON()
method customizes JSON stringification behavior: instead of the object being serialized, the value returned by thetoJSON()
method when called will be serialized.如果对象具有或继承了
toJSON
方法,则该方法的返回值将成为字符串化的目标。您只需读取obj.toJSON
的值即可检查某个对象obj
上是否存在某个对象。
关于node.js - Sequelize POJO JSON.stringify 魔法是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747844/