Search code examples
node.jsexpressmongoosemongoose-schema

Error while trying to save object to MongoDB using mongoose


So I'm trying to save a POST request on /api/register on the MongoDB DBMS using Mongoose node.js + express.

My schema:

const mongoose = require('mongoose');

const obSchema = mongoose.Schema({

    ID: {
        type: Number,
        required: true,
        unique: true
    },
    description: { 
    type: String, 
    required: true
    },
    active: Boolean
});

module.exports = mongoose.model("OB", obSchema);

My code:

<express imports etc>
const OB = require('./models/ob.js');
app.post('/api/register', apiLimiter, async function (req, res){
  try  {
    OB.save(function (err) {
      if (err) return console.error(err);
      console.log("Saved successfully");
    });
  } catch (err) {
    res.status(500).send()
    console.log(err);
  }
});

My error:

TypeError: OB.save is not a function


Solution

  • TypeError: OB.save is not a function

    because you are operating on the raw Mongoose model and not an instance of a model.

    The save function belongs to instances of Mongoose models, and in order to save a document in Mongo you must first instantiate a model:

    const myOb = new OB({ ID: 1234, description: 'qwerty', active: true });
    
    myOb.save((err) => {
      if (err) return console.error(err);
      console.log("Saved successfully");
    });
    

    Mongoose model documentation