如何为人口设置猫鼬模式

How to setup Mongoose Schema for population

我的猫鼬模式有问题。我能够从一个文档填充另一个文档,但我无法在其他文档之间创建类似的连接。

我已经看了很长时间了,但我就是看不出有什么问题。它似乎设置正确,但没有填充注释。我正在使用猫鼬 5.4.5。

blogSchema

const mongoose = require('mongoose')

const blogSchema = mongoose.Schema({
  title: String,
  author: String,
  url: String,
  likes: Number,
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Comment'
    }
  ]
})

blogSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

const Blog = mongoose.model('Blog', blogSchema)

module.exports = Blog

评论架构

const mongoose = require('mongoose')

const commentSchema = mongoose.Schema({
  text: {
    type: String,
    minlength: 3,
    present: true
  },
  blog: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Blog'
    }
})

commentSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

const Comment = mongoose.model('Comment', commentSchema)

module.exports = Comment

userSchema

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')

const userSchema = mongoose.Schema({
  username: {
    type: String,
    unique: true,
    minlength: 3,
    present: true
  },
  name: String,
  passwordHash: String,
  blogs: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Blog'
    }
  ],
})

userSchema.plugin(uniqueValidator)

userSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
    delete returnedObject.passwordHash
  }
})

const User = mongoose.model('User', userSchema)

module.exports = User

填充

router.get('/', async (request, response) => {
  const blogs = await Blog.find({})
    .populate('comment', { text: 1 })
    .populate('user', { username: 1, name: 1 })

  response.json(blogs.map(b => b.toJSON()))
})

我能够将 user 正确填充为 blogSchema,但填充 Comment 不起作用。填充调用的顺序不会改变这种情况,如果我只为 comment 调用填充,它无论如何都不起作用。

我想我的模式有问题,但我就是看不到它。

嗯...在您的博客中它被称为 comments 但您尝试填充 comment。我认为这就是问题所在。