【问题标题】:Referenced model not showing in edit page when using populate使用填充时参考模型未显示在编辑页面中
【发布时间】:2018-03-11 03:34:45
【问题描述】:

在我的应用程序中,我有两个模型 - Book 和 Genre。我使用 Schema.Types.ObjectId 从 Book 模型中引用了 Genre 模型。所以这就是我的模型的样子:

图书模型

const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const Schema = mongoose.Schema

const bookSchema = Schema({
  name: {
    type: String,
    trim: true,
    required: 'Please enter a book name'
  },
  description: {
    type: String,
    trim: true
  },
  author: {
    type: String,
    trim: true,
  },
  category: {
    type: String,
    trim: true
  },
  genre: [{
    type: Schema.Types.ObjectId,
    ref: 'Genre'
  }]
})

module.exports = mongoose.model('Book', bookSchema)

类型模型

const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const Schema = mongoose.Schema

const genreSchema = Schema({
  name: {
    type: String,
    trim: true,
    required: 'Please enter a Genre name'
  }
})

module.exports = mongoose.model('Genre', genreSchema)

在图书编辑页面上,我希望能够显示可用的流派并检查已保存在该特定图书中的流派。

这是我的路线:

router.get('/edit/:id', (req, res, next) => {
  const book = Book.findOne({ _id: req.params.id })
  .populate({
    path: 'genre',
    model: 'Genre',
    populate: {
      path: 'genre',
      model: 'Book'
    }
  })
  .exec()
    .then((book) => {
      const genres = Genre.find({ 'genre': req.params.id })
      res.render('editBook', { book, genres })
    })
    .catch((err) => {
      throw err
    })
})

router.post('/edit/:id', (req, res, next) => {
  req.checkBody('name', 'Name is required').notEmpty()
  req.checkBody('description', 'Description is required').notEmpty()
  req.checkBody('category', 'Category is required').notEmpty

  const errors = req.validationErrors()

  if (errors) {
    console.log(errors)
    res.render('editBook', { book, errors })
  }

  const book = Book.findOneAndUpdate({ _id: req.params.id }, req.body,
  {
    new: true,
    runValidators:true
  }).exec()
  .then((book) => {
    res.redirect(`/books/edit/${book._id}`)
  })
  .catch((err) => {
    res.send({
      'message': err
    })
  })
})

应该显示流派的部分如下所示:

.form-group
          label.col-lg-2.control-label Genre
          .col-lg-10
            for genre in genres
              .checkbox
                input.checkbox(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked)
                label(for=genre._id) #{genre.name}

我可能做错了什么?我已经尝试了所有我知道的解决方案,但没有任何效果。

P.Smongoose-deep-populate插件很久没有更新了。我使用的解决方案适用于表演路线,可以在这里找到 - https://stackoverflow.com/a/43464418/2119604

【问题讨论】:

    标签: node.js mongodb mongoose-schema


    【解决方案1】:

    您错误地使用了猫鼬populate 方法。 populate 返回父模型和引用模型的对象。在您的情况下,book 有一个流派数组(顺便说一句,它在您的架构中有错误的名称,单数而不是复数),因此您不需要额外的请求来加载流派:

    router.get('/edit/:id', (req, res, next) => {
      Book
        .findOne({ _id: req.params.id })
        .populate('genre')
        .exec()
        .then(book => res.render('editBook', { book, genres: book.genre }))
        .catch(err => {
          console.log(err);
          next(err);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      相关资源
      最近更新 更多