Home > Software design >  Express.js cant save mongoose model
Express.js cant save mongoose model

Time:04-29

I need help with this topic, i tried a few things, but nothing is working. I want to save a user in MongoDB. I created The schemantic and export it to user.js

UserModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: {
    type: String
  },
password: {
    type: String
  },
birthdate: {
    type: Date
  },
dateJoined: {
    type: Date,
    default: Date.now()
  }
});

module.exports = mongoose.model('User', userSchema)

User.js

const express = require('express');
const User = require('../models/userModel')
const router = express.Router();

router.post("/register", (req, res) => {

const myUser = new User({
  username: req.body.username,
  password: req.body.password,
  birthdate: req.body.birthdate
});

myUser.save()
   .exec()
   .then(data => {
      res.json(data);
   })
   .catch(err => {
      res.json({Error: err});
   });


});

module.exports = router;

now the error code

Error
Save is not a function

I hope you can find our mistake!

CodePudding user response:

You cannot use .exec() with .save(). I'm pretty sure if you do

myUser.save().then(data => {
      res.json(data);
   })
   .catch(err => {
      res.json({Error: err});
   });

This would work

  • Related