Mongoose 人口不能得到这个工作?

jrcvhitl  于 2023-10-19  发布在  Go
关注(0)|答案(3)|浏览(145)

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 种群不工作。
请让我知道我做错了什么或者给予我一个简单的解释.谢谢.

kg7wmglp

kg7wmglp1#

使用populate加载子文档是正确的,但是需要在novel模式中传递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);

执行输出:

wsewodh2

wsewodh22#

函数populate()上的参数是你想要填充的字段的路径,当你在mongoose中使用populate或任何链接函数时,你必须在结尾使用exec()函数,所以正确的方法是:

Novel.findById('5b87310d41073743856a7c4a').populate({
  path: 'type'
}).exec()
qaxu7uf2

qaxu7uf23#

category.model.js

<!-- begin snippet: js hide: false console: true babel: false -->

相关问题