Using insertOne() in Mongoose

Jul 5, 2022

Mongoose models do not have an insertOne() method, you should use the create() function instead.

const mongoose = require('mongoose');
const schema = new mongoose.Schema({
  name: String
});
const TestModel = mongoose.model('Test', schema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await TestModel.create({
    name: 'Test Testerson'
  });
}
run();

If you are adamant about using insertOne(), you will need to call the function on the collection itself:

const mongoose = require('mongoose');
const schema = new mongoose.Schema({
  name: String
});
const TestModel = mongoose.model('Test', schema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await TestModel.collection.insertOne({ name: 'Test Testerson' });
}
run();

Note: All methods on TestModel.collection bypass Mongoose entirely. So TestModel.collection.insertOne() bypasses schema validation, middleware, getters/setters, and all other Mongoose features.


Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials