【问题标题】:How to setup Mongoose Schema for population如何为人口设置 Mongoose Schema
【发布时间】:2019-10-01 11:11:25
【问题描述】:

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

我已经看了很长时间了,但我只是看不出有什么问题。它似乎设置正确,但没有填充 cmets。我正在使用猫鼬 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

commentSchema

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

用户架构

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 调用填充,它无论如何都不起作用。

我想我的架构有问题,但我只是看不到它。

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!我只是没看到。
    猜你喜欢
    • 2019-02-16
    • 2019-01-19
    • 2021-08-27
    • 2022-01-07
    • 2021-06-19
    • 2021-09-10
    • 2023-02-11
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多