我是后端开发的新手,我在将 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,
required: true,
},
username: {
type: String,
required: true,
},
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,
default: null,
},
bio: {
type: String,
default: null,
},
profilePic: {
type: String,
default: null,
},
username: {
type: String,
default: null,
},
url: {
type: String,
default: null,
},
user: {
type: Schema.Types.ObjectId,
ref: "User",
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Profile", profileSchema);
如果你想看,这里是完整的代码
https://github.com/adityakmr7/medium-clone
任何帮助都会很棒。谢谢你。 我在这里使用 Graphql 和 apollo。