Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: User.save is not a function

I am trying to post the user data to mongodb but I am getting an error as :

TypeError: user.save is not a function

how to fix this?

I am using express

here is my code:

router.post('/', function (req, res) {
  let params = {
    id: req.body.id,
    name: req.body.name
  }
  User
    .save({ params })
    .find()
    .then((data) => {
      res.render('index', { title: 'List', data: data });
    })
    .catch((err) => {
      return res.send(err);
    });
})

This is my schema:

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

var User = new Schema({
    id: String,
    name: String
});

User.pre('save', function (next) {
    next();
});

module.exports = mongoose.model('User', User);
like image 957
HKS Avatar asked Oct 29 '22 06:10

HKS


1 Answers

You have to create a new User instance and call save on it

router.post('/', function (req, res) {
  let user = new User ({
    id: req.body.id,
    name: req.body.name
  })

  user.save((err) => {
                if (err) {
                    return res.send(err);
                }

                User
                 .find()
                 .then((data) => {
                     res.render('index', { title: 'List', data: data });
                 })
                 .catch((err) => {
                     return res.send(err);
                 });
  });
})
like image 149
Ivan Mladenov Avatar answered Nov 10 '22 00:11

Ivan Mladenov