Home > Mobile >  mongoose: save is not a function
mongoose: save is not a function

Time:02-24

Given a user model:

import { model, Schema } from 'mongoose'

export interface User {
  email: string
}

const userSchema = new Schema<User>(
  {
    email: {
      type: String,
      required: true,
    },
  },
)

export const UserModel = model<User>('User', userSchema)

I'm trying to save it as so:

// inside an async function
const newUser: HydratedDocument<User> = new UserModel({
  email: '[email protected]',
})

console.log(newUser)

await newUser.save()

Which results in newUser.save is not a function. What am I missing? Also, here is the output of the `console.log(newUser)

Also, here is the output of the `console.log(newUser)

CodePudding user response:

My stupid mistake: I was calling everything on the fronted. Solution is as easy as moving relevant db calls to the endpoint.

CodePudding user response:

You will need to also define a model, change your schema definition to this:

first create model from Schema :

 var UserModel = mongoose.model('User', User);

then create object out of User model

 var user = new UserModel(req.body)

then call

 user.save(function(){});

check documentation http://mongoosejs.com/docs/api.html#model_Model-save

  • Related