Last active
August 17, 2020 20:25
-
-
Save adi-g15/3d0e1275ad039756f4cde996ff396801 to your computer and use it in GitHub Desktop.
Mongoose Scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Schema, model, connect } = require("mongoose"); | |
connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useCreateIndex: true }, (err) => { | |
if (!err) { | |
console.log('MongoDB Connection Succeeded.'); | |
} else { | |
console.log('Error in DB connection: ' + err); | |
} | |
}); | |
const trial = new Schema({ | |
a: { | |
b1: { alias: 'b.first', type: String }, | |
b2: { alias: 'b.second', type: String} | |
} | |
}); | |
trial.virtual('boss').get(function(){return this.b}) | |
//NOTE -> COMMENT THE ABOVE AND UNCOMMENT THIS, TO USE THE NEW SCHEMA | |
// const trial = new Schema({ | |
// a: { | |
// alias: 'boss', //TypeError: Invalid schema configuration: `Boss` is not a valid type at path `a.alias`. See http://bit.ly/mongoose-schematypes for a list of valid schema types. | |
// b1: { alias: 'b.first', type: String }, | |
// b2: { alias: 'b.second', type: String} | |
// } | |
// }); | |
const trialModel = model( 'trial', trial); | |
let data = { | |
a: 'Hi', | |
b: { | |
b1: 'First', | |
b2: 'Second' | |
} | |
} | |
let doc; | |
trialModel.create(data) | |
.then(newDoc => { doc = newDoc; console.log(newDoc.boss.joiner); }) | |
.catch(err => console.log(err.code)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Run the script... duplicates won't be created | |
GET /post ... duplicates won't be created | |
GET /delete, then GET /post... DUPLICATES CREATED | |
Just looking at console output is enough to get if there is a problem | |
*/ | |
const express = require('express') | |
const app = express() | |
const { Schema, Types, connect, model, connection } = require('mongoose') | |
connect('mongodb://localhost/DUPLICATE15', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}) | |
.then(val => console.log('Connected to mongo')) | |
.catch(err => console.error('โโ Couldn\'t establish connection to MongoDB')) | |
connection | |
.on('error', err => console.log(err.code) ) | |
.once('open', () => console.log('๐ Open to connection') ) | |
//CATEGORY | |
const categorySchema = new Schema({ | |
name: { | |
type: String, | |
unique: true, | |
}, | |
todoIds: { | |
type: [Types.ObjectId], | |
} | |
}) | |
const categoryModel = model('categories', categorySchema) | |
const todoSchema = new Schema({ | |
title: String, | |
category: String, | |
}) | |
todoSchema.post('save', async function(doc){ | |
//@ISSUE - Two categories with same name, are being created, even though name should be unique | |
await categoryModel.findOne({name: doc.category}, async (err, catDoc) => { | |
if(err){ return console.log('Error while getting', 'Collection: category', 'Path: todoPostSave') } | |
else if(!catDoc){ | |
console.log('โน Going to create collection with name: ', doc.category) | |
if(categoryModel.countDocuments({name: doc.category}, (err, count) => { //[DEBUG] For debugging purpose | |
if(err){ console.log('Error in counting') } | |
console.log(`{name: ${doc.category}} count =`, count) | |
})) | |
categoryModel.create({ //async... not using await here | |
name: doc.category, | |
todoIds: [doc._id] | |
}).then((addedCatDoc) => { | |
console.log('๐ Created category: ', addedCatDoc.name); | |
}) | |
.catch(err => console.error('ERROR in creating category ', err.code == 11000 ? 'DuplicateKey': '')) | |
} | |
}) | |
}) | |
const todoModel = model('todos', todoSchema) | |
let todos = [ | |
{ title: 't1', category: 'something' }, | |
{ title: 't2', category: 'something' }, | |
{ title: 't3', category: 'something' } | |
] | |
// THE CODE OUTSIDE ANY REQUEST HANDLER - begin | |
let todo2 = [{ title: 'sec1', category: 'trial'},{ title: 'sec2', category: 'trial' }] | |
todoModel.create(todo2, (err, docs) => { | |
if(err){ | |
return console.log('! Error while creating todo ', err.code); | |
} | |
console.log('All todos were added successfully') | |
}) | |
// THE CODE OUTSIDE ANY REQUEST HANDLER - end | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: false })); | |
app.get('/post', (req, res) => { | |
console.log('received post request'); | |
todoModel.create(todos, (err, docs) => { | |
if(err){ | |
return res.status(500).send('! Error while creating todo ', err.code); | |
} | |
res.send('All todos were added successfully') | |
}) | |
}) | |
app.get('/delete', async (req, res) => { | |
console.log('received deleteAll request'); | |
await connection.dropDatabase() | |
res.send('Done'); | |
}) | |
app.get('/', async (req, res) => { | |
console.log('received getCategories request'); | |
await categoryModel.find({}, (err, docs) => { | |
if(err) return res.sendStatus(500) | |
res.send(docs) | |
}) | |
}) | |
const PORT = process.env.PORT || 3000 | |
app.listen(PORT, () => {console.log(`listening on port ${PORT}....`)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment