1

遇到了问题。我有两个模型:

//Comment.js

module.exports = (sequelize, DataTypes) => {
    const Comment = sequelize.define('Comment', {
        body: {
            type: DataTypes.STRING,
            unique: true,
            notEmpty: true
        },

        createdAt: {
            type: DataTypes.DATE,
            defaultValue: DataTypes.NOW
        },
    }, {
        timestamps: false
    });

    Comment.associate = (models) => {
        Comment.belongsTo(models.User, {as: 'owner'}),
        Comment.belongsToMany(models.Comment, {as: 'Children', through: 'CommentChildren'}),
        Comment.hasOne(models.Comment, {as: 'Parent', foreignKey: 'ParentId', onDelete: 'CASCADE' })
    }

    return Comment
}

//User.js

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        login: {
            type: DataTypes.STRING,
            unique: true,
            notEmpty: true
        },

        password: {
            type: DataTypes.STRING,
            notEmpty: true,
            allowNull: false
        },

        status: {
            type: DataTypes.ENUM('active', 'inactive'),
            defaultValue: 'active'
        }
    }, {
        timestamps: true
    });

    User.associate = (models) => {
        User.hasMany(models.Post)
    }

    return User
}

评论存储在评论模型中,评论可以有父评论,也可以有很多子评论。

当我尝试执行查询时:

const comments = await models.Comment.findAll({
                    where: {PostId: post.id},
                    include: [{model: models.User, as: 'owner'}, {model: models.Comment, as: 'Children'}]
                }).catch(console.log)

当你尝试在 中显示这个结构时EJS,第一级的结果集可以访问{model: models.User, as: 'owner'}via comments[0].owner.login,但子级没有这个属性。

//Comment.ejs

<% if (items) { %>
  <% if (items.length) { %>
      <ul>
        <% } %>

          <% items.forEach(function(item){ %>
            <li id="<%= item.id %>">
              <div class="head">
                <a href="/users/<%= item.owner.login %>">
                  <%= item.owner.login %>
                </a>
                <spam class="date">
                  <%= moment(item.createdAt).fromNow(); %>
                </spam>
              </div>
              <%= item.body %>
                <span class="link" id="reply">Reply</span>
                <% if (item.Children) {%>
                  <%= include('./comments.ejs', {items: item.Children}) %>
                <% }%>
            </li>
            <% }) %>

              <% if (items.length) { %>
      </ul>
  <% } %>
<% } %>

如果您创建没有子元素的元素,一切正常,但一旦创建子注释,就会引发错误,指示加深的元素无权访问{model: models.User, as: 'owner'}

    7|             <li id="<%= item.id %>">
    8|               <div class="head">
 >> 9|                 <a href="/users/<%= item.owner.login %>">
    10|                   <%= item.owner.login %>
    11|                 </a>
    12|                 <spam class="date">

Cannot read property 'login' of undefined

如何修改查询以在 mangoose 中填充类似内容?

4

0 回答 0