如何解决如何在nodejs中将用户模型与配置文件模型连接起来
我是后端开发的新手,我在将 User
模型与 Profile
模型连接时遇到了一些问题。当用户在 username
模型中设置它们时,我还想在配置文件模型中自动生成 User
。我不知道该怎么做。这是我的代码
Resolver.js
Mutation: {
signUpUser: async (parent,{ userInput }) => {
const { email,username,password } = userInput;
const errors = [];
if (!validator.isEmail(email)) {
errors.push({
message: "Invalid Email",});
}
const existingUser = await User.findOne({ email: email });
if (existingUser) {
const error = new Error("User exists already");
throw error;
}
if (errors.length > 0) {
const error = new Error("Invalid Input");
error.data = errors;
error.code = 402;
throw error;
}
const hashedPassword = await bcrypt.hash(password,12);
const user = new User({
email: email,password: hashedPassword,username: username,});
const createdUser = await user.save();
return {
...createdUser._doc,_id: createdUser._id.toString(),};
},
用户模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new mongoose.Schema(
{
email: {
type: String,required: true,},password: {
type: String,username: {
type: String,status: {
type: String,default: "I am new!",posts: [
{
type: Schema.Types.ObjectId,ref: "Post",],profile: {
type: Schema.Types.ObjectId,ref: "Profile",{ timestamps: true }
);
module.exports = mongoose.model("User",userSchema);
配置文件模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const profileSchema = new mongoose.Schema(
{
firstName: {
type: String,default: null,lastName: {
type: String,bio: {
type: String,profilePic: {
type: String,url: {
type: String,user: {
type: Schema.Types.ObjectId,ref: "User",}
},{ timestamps: true }
);
module.exports = mongoose.model("Profile",profileSchema);
如果你想看,这里是完整的代码
https://github.com/adityakmr7/medium-clone
任何帮助都会很棒。谢谢你。 我在这里使用 Graphql 和 apollo。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。