book.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const BookSchema = new Schema({
name: {
type: String,
required: true
}
})
module.exports = BookSchema
book.model.js
const mongoose = require('mongoose')
const BookSchema = require('../schema/book.schema')
const Book = mongoose.model('Book', BookSchema)
module.exports = Book
novel.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const NovelSchema = new Schema({
name: {
type: String,
required: true
},
type: {
type: Schema.Types.ObjectId,
ref: 'Book'
}
})
module.exports = NovelSchema
novel.model.js
const mongoose = require('mongoose')
const NovelSchema = require('../schema/novel.schema')
const Novel = mongoose.model('Novel', NovelSchema)
module.exports = Novel
查询
// Mongoose Populate cant get this to work
// I am at a loss
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'books'
})
Mongoose 种群不工作。
请让我知道我做错了什么或者给予我一个简单的解释.谢谢.
3条答案
按热度按时间kg7wmglp1#
使用populate加载子文档是正确的,但是需要在novel模式中传递book字段的名称,在本例中,名称是type。
以下是一些示例的文档链接:Mongoose Populate
下面是解决您的问题的更多方法:
执行输出:
wsewodh22#
函数populate()上的参数是你想要填充的字段的路径,当你在mongoose中使用populate或任何链接函数时,你必须在结尾使用exec()函数,所以正确的方法是:
qaxu7uf23#