我使用Sequelize作为我的ORM。我有一个简单的User
模型如下。 Qazxswpoi User
hasMany
和comments
Comment
a belongsTo
。
user
(修剪到相关的)
models/user.js
const model = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING
}
},
{
classMethods: {
associate: function(models) {
User.hasMany(models.Comment, {as: 'comments'})
}
}
}
)
return User
}
module.exports = model
(也修剪)
models/comment.js
我创建了一个测试如下(为简洁而修剪)
const model = (sequelize, DataTypes) => {
const Comment = sequelize.define('Comment', {
text: {
type: DataTypes.TEXT
}
}, {
classMethods: {
associate: function(models) {
Comment.belongsTo(models.User, {as: 'author'})
}
}
}
)
return Comment
}
module.exports = model
结果
describe('create user given simple valid data', () => {
const userData = {
name: 'test'
}
it('creates a user', (done) => {
User.create(userData, {
include: [{model: models.Comment, as: 'comments'}]
}).then((user) => {
const userJS = user.get({plain: true})
expect(userJS).to.have.property('name')
expect(userJS).to.have.property('comments')
done()
}, done)
})
})
如果我这样指定我的Unhandled rejection AssertionError: expected { Object (name, ...) } to have a property 'comments'
userData
测试通过就好了。
我怎么能告诉Sequelize只是将一个空的评论列表作为默认值?
实际上,此功能不是模型创建的一部分。
它与获取数据时的查询有关。您可以在findAll的include语句中使用nested:true选项。
const userData = {
name: 'test',
comments: []
}
来源:User.findAll({
include: [{
model: Comment,
as: "comments",
nested: true
}]});