温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

node js orm 框架 sequelize 的findOne 与findAll 一点使用心得

发布时间:2020-05-25 23:02:32 来源:网络 阅读:5014 作者:蠢蠢的蜗牛 栏目:web开发
     sequelize 的findOne 与findAll 的使用

Js

    User.js:
var Sequelize = require('sequelize');
var sequelize = require('./../dataconfig');

// // 创建 model
var User = sequelize.define('user', {
id: { type: Sequelize.INTEGER, 'primaryKey': 'true' },
userName: {
        type: Sequelize.STRING, // 指定值的类型
        field: 'user_name' // 指定存储在表中的键名称
},
// 没有指定 field,表中键名称则与对象键名相同,为 email
email: {
        type: Sequelize.STRING
}
}, {
        // 如果为 true 则表的名称和 model 相同,即 user
        // 为 false MySQL创建的表名称会是复数 users
        // 如果指定的表名称本就是复数形式则不变
        freezeTableName: true
});

exports.findAllUser = function () {
return User.findAll();
}

写个测试类 test.js:

//test.js 调用

var user = require('./model/user');

user.findAllUser().then(result => {
    console.log('用户数据sss', result)
})

运行

node test.js

node js orm 框架 sequelize 的findOne 与findAll 一点使用心得

???跟我想的不一样呀,我只要一个json数组就可以了 defaultvalues 是什么鬼?

原来返回的不是json对象,而是包装了一层的 Instance

Instance类表示一个实例,表示数据库中的一行。它不能通过构造函数实例化,而应该通过Model.find*或Model.create等方法创建。

实例中包含一个dataValues属性,其中存储了实例实际所要操作的值。dataValues中的值可以通过以下几种方式访问:

instance.field
// 等价于
instance.get('field')
// 等价于
instance.getDataValue('field')
如果定义了访问器(getter)/设置器(setter),字段值从其中访问而不是从dataValues。一般会直接访问或使用get来访问属性值,而getDataValue只用于自定义的访问器。

或者加上{row:true}
node js orm 框架 sequelize 的findOne 与findAll 一点使用心得

再次运行 node test.js

node js orm 框架 sequelize 的findOne 与findAll 一点使用心得

成功,仅仅写给小白,大佬请略过,不要笑话我,溜了溜了。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI