Как настроить схему мангуста для населения - PullRequest
0 голосов
/ 14 мая 2019

У меня проблема с моей схемой мангуста. Мне удалось заполнить один документ другим, но я не могу создать аналогичную связь между другими документами.

Я давно смотрю на это, но я просто не вижу, в чем дело. Вроде бы все правильно, но комментарии не заполняются. Я использую мангуст 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

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, это все равно не сработает.

Я полагаю, что есть проблема с моими схемами, но я просто не могу ее увидеть.

1 Ответ

1 голос
/ 14 мая 2019

Хорошо ... В вашем блоге это называется comments, но вы пытаетесь заполнить comment.Я думаю, что это проблема.

...