. insertOne Is Not a Function

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?

4 Answers

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) {
2

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) {
    // ...
})

edit

as of mongoose documentation, try using

Account.create({ ...params ... }, function (err, small) {
  if (err) return handleError(err);
  // saved!
})

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}
    }
  }
}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest