mongoose create document code example

Example 1: mongoose save or update

// This will create another document if it doesn't exist
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });

Example 2: mongoose model

const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);

Example 3: create document mongoose

var Tank = mongoose.model('Tank', yourSchema);

var small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {

});

Example 4: mongoose add document

const Product = require('../models/product.js');

const product = new Product();
product.save()
		.then(doc => {})
        .catch(err => {});

Tags:

Misc Example