node.jsmongodbmongoosekoa

Mongoose Populate cant get this to work?


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

query

// Mongoose Populate cant get this to work
// I am at a loss
Novel.findById('5b87310d41073743856a7c4a').populate({
  path: 'books'
})

mongoose populate not working。

Please let me know what I am doing wrong or give me a simple explanation...Thank you...


Solution

  • You are right to use the populate for loading the subdocument, but you need to pass the name of the book field in the novel schema, in your case the name is type.

    Here is the link to documentation with some examples: Mongoose Populate

    And below is the more one solution to your problem:

    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);
    

    And the execution output:

    execution output