mongoose save() 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: node mongoose save document

// Example for a model called Person with two properties, e.g. name, surname
// Values to be saved
const person = { name: Jane, surname: Doe};
// you can access the _id property from savedPerson variable (savedPerson._id)
savedPerson = await new Person(person).save()

Example 5: model mongoose

const modelName = mongoose.model("collectionname", collectionSchema);

//example
const fruitSchma = new mongoose.Schema ({
  name: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);

Example 6: mongoose save a document

const Person = mongoose.model('Person', Schema({
  name: String,
  rank: String
}));

const doc = new Person({
  name: 'Will Riker',
  rank: 'Commander'
});
// Inserts a new document with `name = 'Will Riker'` and
// `rank = 'Commander'`
await doc.save();

const person = await Person.findOne();
person.name; // 'Will Riker'