const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bookStore', { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB..'))
.catch(err => console.log('Error! Could not Connect to Mongodb..', err));
// Creating MongoDB Schema
const bookSchema = new mongoose.Schema({
name: String,
author: String,
category: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
price: Number,
isPublished: Boolean
});
// Creating MongoDB Model for book
const Book = mongoose.model('Book', bookSchema);
// Creating new book using Async function to avoid sync method
async function createBook(){
const book = new Book({
name: 'JavaScript: The Definitive Guide',
author: 'David Flanagan',
category: 'Programming',
tags: ['javascript', 'programming'],
price: 20,
isPublished: true
});
const result = await book.save();
console.log(result);
}
// createBook();
// Query all data from the Mongodb table
async function getBook(){
return await Book
.find({ isPublished:true, category: /.*programming.*/i })
.sort({ name:1 })
.limit(2)
.select({name:1, price:1});
}
async function run(){
const books = await getBook();
console.log(books)
}
// run();
// Update document in MongoDB - Query First Approach
async function updateBook(id){
const book = await Book.findById(id);
if(!book) return;
// Method One
book.isPublished = true;
book.author = 'Kyle Himson';
book.price = 100;
// Method Two
/* book.set({
isPublished: true,
authorL: 'Updated Author'
}); */
const result = await book.save();
console.log(result);
}
//updateBook('5c17b61be1af3c042ab793ce');
// Update document in MongoDB - Update First Approach
async function updateBookFirst(id){
const result = await Book.findByIdAndUpdate(id, {
$set:{
author: 'Sadia Farjana',
isPublished: false,
price: 115
}
});
console.log(result);
}
//updateBookFirst('5c184756cda9ad072ba93330');
// Deleting document from the MongoDB
async function removeBook(id){
const book = await Book.findByIdAndRemove(id);
console.log(book);
}
//removeBook('5c18986bd08fc008cd011c05');
const mongoose = require('mongoose');
// Connected to the MongoDB
mongoose.connect('mongodb://localhost/playground', {
useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB Database...'))
.catch(err => console.log('Error! Could not Connect to Mongodb..', err))
// Creating MongoDB Schema with property and data type (it's like an SQL table design)
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
isPublished: Boolean
});
// Mongoose model creating it return object Class
const Course = mongoose.model('course', courseSchema);
// Creating Async function to avoid late and creating new course object
async function createCourse() {
const course = new Course({
name: 'Angular',
author: 'Hasib',
tags: ['angualr', 'FrontEnd'],
isPublished: true
});
const result = await course.save();
console.log(result);
}
createCourse();