1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Angular MEAN stack model/controller not saving to MongoDB Atlas

Discussão em 'Angular' iniciado por Zayno lane, Setembro 28, 2024 às 06:43.

  1. Zayno lane

    Zayno lane Guest

    I'm following a tutorial, and I'm stuck on this problem, The model is not passing data to the MongoDB Atlas Database. I'm trying to post data with Postman, but I get a status 200 ok, but it does not give me a status 201 "user created successfully." I suspect that the Mongoose schema in the model is not correct. I read the Mongoose docs, but I keep having the same problem. here are the code snippets:

    UserModel.js



    const UserSchema = new mongoose.Schema({
    username: { type: String, required: true, min: 4, unique: true },
    password: { type: String, required: true },
    });
    const User = mongoose.model("users", UserSchema);
    export default User;


    fault in UserModel.js;

    the tutorial says use username:{types:String, etc...},


    but I get an error TypeError: Invalid schema configuration: true is not a valid type at path required, and in the mongoose docs it describes that you should use username:{type: String, etc...},

    AuthController.js

    export const signup = async (req, res) => {
    const { username, password } = req.body;
    const hashedPassword = bcryptjs.hashSync(password, 10);
    const newUser = new User({ username, password: hashedPassword });
    try {
    const existingUser = await User.findOne({ username });
    if (existingUser) {
    throw errorHandler(409, "User already exists in database!");
    }
    await newUser.save();
    res.status(201).json("User has been created successfully!");
    } catch (error) {
    console.error(error.message);
    res.status(error.statusCode).json(error.message);
    }
    };


    Index.js

    const app = express();
    app.use(express.json());
    dotenv.config();
    app.use(cookieParser());
    app.listen(process.env.Server, () =>
    console.log("Server is runnning on port 4000!")
    );

    app.use("/", async (req, res) => {
    try {
    res.json("Hello from Mongo server!");
    } catch (error) {
    console.error(error);
    res.status(500).json("Error:500 Internal server error!");
    }
    });
    mongoose
    .connect(process.env.MongoDB)
    .then(() => {
    console.log("successfully Conected to MongoDB!");
    })
    .catch((err) => console.log(err));
    const corsOptions = {
    origin: function () {
    if (!origin) return callback(null, true);
    if (process.env.ALLOWED_ORIGINS) {
    callback(null, true);
    } else {
    callback(new Error("server not allowed by CORS!"));
    }
    },
    credentials: true,
    };

    app.use(cors(corsOptions));
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const storage = multer.diskStorage({
    destination: (req, file, cb) => {
    cb(null, path.join(__dirname, "public"));
    },
    filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
    },
    });

    export const upload = multer({ storage });
    app.use((req, res, next) => {
    req.upload = upload;
    next();
    });

    app.use("/api/auth", authRouter);
    app.use("/api/post", postRouter);
    app.use("/api/post/upload", upload.single("file"), postRouterUpload);
    app.use("/upload", express.static(path.join(__dirname, "public")));


    I revised the tutorial twice to see if i didn't make any typo's and read the mongoose documentation on using the proper schema types

    Continue reading...

Compartilhe esta Página