Is it possible to create a new database in MongoDB with Mongoose?

前端 未结 2 1968
北海茫月
北海茫月 2021-02-13 19:00

I am trying to figure out if I can create a new database in MongoDB with Mongoose. I am running on Node, and I know the MongoDB driver for Node can do it, but I am wondering if

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 19:48

    Just Try this code it's very simple and clean

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/yourdatabasename').then(() => console.log('Connected to MongoDB...')).catch((err) => console.error("Coudn't connect MongoDB....", err));
    
    const customerSchema= new mongoose.Schema({ name: String,address: String,email:String,});
    
    const Customer= mongoose.model('Customer',courseSchema);
    
    async function createNewCustomer() {const customer= new Customer({name: 'new customer',address: 'new address',email: 'customer1@new.com',});const result = await customer.save();console.log(result);
    }
    createNewCustomer();
    

提交回复
热议问题