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'
})
猫鼬无法正常工作。
请让我知道我在做错什么,或者给我一个简单的解释...谢谢...
答案 0 :(得分:0)
函数populate()上的参数是您要填充的字段的路径,并且当您在猫鼬中使用填充或任何链接函数时,您必须在末尾使用exec()函数,因此正确这样做的方式是:
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'type'
}).exec()
答案 1 :(得分:0)
您可以使用填充来加载子文档,但是您需要在新颖模式中传递book字段的名称,在这种情况下,名称为 type 。
以下是一些示例的文档链接:Mongoose Populate
下面是解决问题的另一种方法:
let book = await new BookModel({name:"book test"}).save();
console.log('-----------BOOK ITEM-------------');
console.log(book);
let novel = await new NovelModel({name:"novel test",type:book._id}).save();
console.log('-----------NOVEL ITEM-------------');
console.log(novel);
let itemPopulated = await NovelModel.findById(novel._id)
.populate('type')
.then((result) => {
return result;
}).catch((err) => {
console.log(err);
});
console.log('-----------ITEM POPULATED-------------');
console.log(itemPopulated);
执行输出: