19

I want to preface this by saying I have read several posts here regarding this issue.

I have a node/express/mongo app with the following:

app.js:

    var express = require('express')
    var bodyParser = require('body-parser')
    var cors = require('cors')
    var morgan = require('morgan')
    var mongoose = require('mongoose')
    var passport = require('passport')

    var app = express()

    // MongoDB Setup
    var configDB = require('./config/database.js')
    mongoose.connect(configDB.url)

    app.use(morgan('combined'))
    app.use(bodyParser.json())
    // Check security with this
    app.use(cors())
     // load our routes and pass in our app and fully configured passport

    require('./routes')(app)
    app.listen(process.env.PORT || 8081)
    console.log('We are up and running, captain.')

routes.js

const AuthenticationController = require('./controllers/AuthenticationController')

module.exports = (app) => {
  app.post('/register', AuthenticationController.register)
}

My mongo schema file Account.js:

const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const Schema = mongoose.Schema

var accountSchema = new Schema({
  email: String,
  password: String,
  likesPerDay: { type: Number, min: 0, max: 250 },
  followPerDay: { type: Number, min: 0, max: 250 },
  unfollowPerDay: { type: Number, min: 0, max: 250 },
  commentsPerDay: { type: Number, min: 0, max: 250 },
  comment: String,
  hashtags: [String]
})

// methods ======================
// generating a hash. We hash password within user model, before it saves to DB.
accountSchema.methods.generateHash = function (password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
}

// checking if password is valid
accountSchema.methods.validPassword = function (password) {
  return bcrypt.compareSync(password, this.local.password)
}

// create the model for users and expose it to our app
module.exports = mongoose.model('Account', accountSchema)

And finally my controller file AuthenticationController.js

const Account = require('../models/Account.js')
// var bodyParser = require('body-parser')

module.exports = {
  register (req, res) {
    Account.findOne({email: req.body.id}, function (err, account) {
      if (err) {
        console.log('Could not regster user')
        throw err
      }
      if (account) {
        console.log('account already exists')
      } else {
        Account.insertOne({email: req.body.email, password: req.body.password}, function (err, res) {
          if (err) {
            console.log('could not insert')
            throw err
          }
          console.log('inserted account')
          Account.close()
        })
      }
    })
  }
}

I am getting an error in my AuthenticationController file when I call Account.insertOne function.

I get the error that

TypeError: Account.insertOne is not a function

Now several of the posts here on stack have advised that I make sure that I am exporting the model from my model class, which I am doing, and that would fix this issue. Its weird because the findOne method seems to be fine, but when I call the insertOne i get an issue.

Am I missing something here?

3gth
  • 550
  • 5
  • 23
mufc
  • 695
  • 3
  • 16
  • 31

4 Answers4

51

A Mongoose model doesn't have an insertOne method. Use the create method instead:

Account.create({email: req.body.email, password: req.body.password}, function (err, doc) {
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I was previously using `updateOne` with `upsert`, and I noticed that `create` will create a key called `__v`. How do I disable this? – Aaron Franke Oct 31 '20 at 03:30
  • @AaronFranke Does this help? https://stackoverflow.com/questions/13699784/mongoose-v-property-hide Better late than never – MasterMind Apr 14 '21 at 14:10
8

The Mongoose docs show how to create documents:

Either via Account.create():

Account.create({email: req.body.email, password: req.body.password}, function (err, res) {
    // ...
})

Or by instantiating and save()ing the account:

new Account({email: req.body.email, password: req.body.password}).save(function (err, res) {
    // ...
})
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

edit

as of mongoose documentation, try using

Account.create({ ...params ... }, function (err, small) {
  if (err) return handleError(err);
  // saved!
})
Roberto Bisello
  • 1,235
  • 10
  • 18
1

insertOne command is not available in mongoose directly as mentioned in Mongoose Documentation. If you want to use insertOne command then you need to use bulk command in order to send this command to MongoDB server. Something like below. I hope this works.

Account.bulkWrite([
  {
    insertOne: {
      document: {email: req.body.email, password: req.body.password}
    }
  }
}]
Actung
  • 1,438
  • 1
  • 13
  • 18