Vue方法为帖子创建消息
createMessage() {
const variables = {
userId: this.user._id,
postId: this.postId,
messageBody: this.message
};
console.log(this.message);
this.$apollo
.mutate({
mutation: CREATE_MESSAGE,
variables,
update: (cache, { data: { createMessage } }) => {
const data = cache.readQuery({
query: CLOSE_UP,
variables: { postId: this.postId }
});
data.closeUp.messages.unshift(createMessage);
cache.writeQuery({
query: CLOSE_UP,
variables: { postId: this.postId },
data
});
}
})
.then(({ data }) => {
console.log(data);
})
.catch(e => console.dir(e));
}
询问
closeUp: async (_, { postId }, { Post }) => {
const post = await Post.findOne({ _id: postId }).populate({
path: 'messages.messageUser',
model: 'User'
});
console.log(post);
return post;
创建消息解析器
export const CREATE_MESSAGE = gql mutation($userId: ID!, $postId: ID!, $messageBody: String!) { createMessage(userId: $userId, postId: $postId, messageBody: $messageBody) { messageBody } }
;
类型定义
type Token {
token: String!
}
type User {
_id: ID
email: String!
username: String!
password: String!
avatar: String
joinDate: String!
favorites: [Post]
}
type Post {
_id: ID
title: String!
description: String!
imageUrl: String!
createdBy: User!
createdDate: String
messages: [Message]!
}
type Message {
_id: ID
messageBody: String!
messageDate: String!
messageUser: User!
}
type PostsPage {
posts: [Post]
hasMore: Boolean
}
type Query {
getCurrentUser: User
getPosts: [Post]
infiniteScrollPosts(pageNum: Int!, pageSize: Int!): PostsPage
closeUp(postId: ID, userId: ID): Post!
}
type Mutation {
addPost(
title: String!
description: String!
creatorId: ID!
imageUrl: String!
createdDate: String
): Post!
createUser(email: String!, username: String!, password: String!): Token
signinUser(username: String!, password: String): Token
createMessage(userId: ID!, postId: ID!, messageBody: String!): Message!
}
楷模
发布模型
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
imageUrl: {
type: String
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
createdDate: {
type: Date,
default: Date.now
},
messages: [
{
messageBody: {
type: String,
required: true
},
messageDate: {
type: Date,
default: Date.now
},
messageUser: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
}
]
});
module.exports = mongoose.model('Post', PostSchema);
用户模型
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true
},
username: {
type: String,
required: true,
trim: true
},
password: {
type: String,
required: true,
trim: true
},
avatar: {
type: String
},
joinDate: {
type: Date,
default: Date.now
},
favorites: {
type: [mongoose.Schema.Types.ObjectId],
required: true,
ref: 'Post'
}
});
我当前在控制台中看到的错误显示“字段'消息'必须是一个数组,但在文档中是对象类型” . graphQl模式类型Post消息中的字段设置为数组 . 我试图将我创建的消息作为帖子的一部分 . 这是我第一个使用graphQl和vue-apollo的项目,所以我确定我错过了一些东西 . 提前致谢 .