express - 我应该如何在 Mongoose 中连接 Schema 模型?
问题描述
我想做一个用户,发布和评论。将它们连接在一起,当我创建一个帖子时,它应该连接到我的一个用户。我不知道为什么我得到一个不寻常的错误。错误:
ID cannot represent value: <Buffer 5e 9b f1 3e e9 49 61 38 fc 1a 6f 59>
这些都是我的代码,所以如果你知道我的问题,请帮我解决它。谢谢
类型定义:
import { gql } from 'apollo-server-express';
export const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
age: Int
posts: [Post!]!
comments: [Comment!]!
}
type Post {
id: ID!
title: String!
body: String!
published: Boolean!
author: User!
comments: [Comment!]!
}
type Comment {
id: ID!
text: String!
author: User!
post: Post!
}
`
用户架构:
import mongoose, { mongo } from 'mongoose';
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
age: {
type: Number,
required: false
},
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
],
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}
]
});
module.exports = mongoose.model('User',userSchema);
后架构:
import mongoose from 'mongoose';
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
published: {
type: Boolean,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}
]
});
module.exports = mongoose.model('Post',postSchema);
评论架构:
import mongoose from 'mongoose';
const commentSchema = new mongoose.Schema({
text: {
type: String,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
module.exports = mongoose.model('Comment',commentSchema);
解析器:
import Users from './models/User';
import Posts from './models/Post';
import Comments from './models/Comment';
export const resolvers = {
Mutation: {
createUser: async (parent, args, context, info) => {
const user = new Users(args);
await user.save();
return user;
},
createPost: async (parent, { title, body, published, author }, context, info) => {
const user = await Users.findById(author);
if (!user) {
console.log("User not found")
}
console.log(user)
const post = new Posts({ title, body, published, author: user.id });
await post.save();
user.posts.push(post);
await user.save();
return post;
}
}
}
解决方案
我找到了解决方案,您应该使用type: mongoose.Schema.Types.ObjectId
,ref: 'Comment'
然后在解析器内部使用population。
推荐阅读
- python - 嵌套python列表和字典问题的问题
- python - Beautifulsoup 查找元素
- c++ - 关于在 C++ 中使用 { } 初始化向量
- c - 如何让 fread() 从内存中读取数据?
- c++ - 排序 an 在用户定义的函数中产生问题
- android - 将使用 SHA-1 密钥的 android 项目转移到另一台电脑
- python - Python Selenium - 获取具有日期角色名的元素
- jenkins-pipeline - 在 Jenkins 中将 DSL 作业转换为管道
- laravel - 带有两个参数的 URL
- python - Python“graphics.py”库工作,但没有方法 .yUp()