mongoose save to db code example

Example 1: mongoose setup

// getting-started.js
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/name", { useUnifiedTopology: true, useNewUrlParser: true });

Example 2: 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 3: node js + mongoose

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

Example 4: 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'

Tags:

Misc Example