【发布时间】: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.S:mongoose-deep-populate插件很久没有更新了。我使用的解决方案适用于表演路线,可以在这里找到 - https://stackoverflow.com/a/43464418/2119604
【问题讨论】:
标签: node.js mongodb mongoose-schema