javascript 使用NodeJS和Mongoose的MongoDB CRUD操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用NodeJS和Mongoose的MongoDB CRUD操作相关的知识,希望对你有一定的参考价值。

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();

以上是关于javascript 使用NodeJS和Mongoose的MongoDB CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章

nodejs如何使用mongo数据库

Nodejs + Mongo db 使用用户名和密码连接服务器数据库

NodeJS + Mongo - 如何获取集合的内容?

NodeJS/Mongo:通过各种集合循环查询

NodeJS + Express + Mongo Session 存储

nodejs中的多个异步mongo请求