This is my app.js file. Please help me out to connect it with my local database. Sometimes it gets connected to the database and logs to the console but it doesn’t add any collection to the local database.
const mongoose = require('mongoose')
main().catch(err=>console.log(err))
async function main() {
await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
//Creating new schema
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit ({
name: "Apple",
rating: 7,
review: "Pretty solid"
});
await fruit.save()
}
2
Answers
Insist localhost use 127.0.0.1:27017 This will work for sure.
OR
This happened probably because the MongoDB service isn’t started. Follow the below steps to start it:
The server will start. Now execute npm start again and the code might work this time.
You can use mongo connection like this in typescript for ES6.
Schema like below
example connection like below
To save your data like