Skip to content

Instantly share code, notes, and snippets.

@gaurang847
Created December 1, 2020 06:50
Show Gist options
  • Select an option

  • Save gaurang847/c96269e4c49046c8d36e951a393d6186 to your computer and use it in GitHub Desktop.

Select an option

Save gaurang847/c96269e4c49046c8d36e951a393d6186 to your computer and use it in GitHub Desktop.
Sample file that uses mongoose to connect to a MongoDB instance and performs simple CRUD operations.
const mongoose = require( 'mongoose' );
const util = require('util');
const Schema = mongoose.Schema;
const CommentSchema = new Schema({
username : String,
content : String,
created : Date
});
const Comment = mongoose.model( 'Comment', CommentSchema );
(async function (){
const conn = await mongoose.connect( 'mongodb://localhost:27017', { useNewUrlParser: true, useUnifiedTopology: true } );
await Comment.create({ username: 'user1', content: 'myContent', created: new Date });
await Comment.updateOne({ username: 'user1' }, { content: 'updated content' });
const comment = await Comment.findOne({ username: 'user1' });
console.log(`user1: ${util.inspect(comment.toJSON())}`);
await Comment.deleteOne({ username: 'user1' });
await conn.disconnect();
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment