我的猫鼬模式有问题。我能够从另一个文档中填充一个文档,但无法在另一文档之间创建类似的连接。
我已经看了很长时间了,但是我只是看不出有什么问题。它似乎已正确设置,但未填充注释。我正在使用猫鼬5.4.5。
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
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
填充填充,则将无法正常工作。
我想我的模式有问题,但是我看不到它。
答案 0 :(得分:1)
好吧...在您的博客中,其名为comments
,但您尝试填充comment
。我认为这就是问题所在。