Unique Property of MongoDB is not working with Mongoose Node.js.

Unique Property of MongoDB is not working with Mongoose Node.js. Data is continuously inserting in database. You can find the image too. I am a very initial stage of learning MongoDB with node.js.

const app =  express()
const port = 3000
const mongoose = require('mongoose')

mongoose.connect('mongodb://127.0.0.1:27017/gofuel').then(con=>{
    console.log("Connected", con);
}).catch(err=>{
    console.log(err);})

app.listen(port,()=>{
    console.log(`App is listening on Port ${port}`);
})

app.get('/',(req, res)=>{
    run()
    res.json({
        status : "200"
    })
})

const Users = mongoose.Schema({
    name :{
        type: String,
        unique: true
    }
}) 

const UserModel = mongoose.model('users', Users)

async function run(){
    const user = await new UserModel({
        name : "ndf"
    })

await user.save().then(res=>{
        console.log("User Created", res);
    }).catch(err=>{
        console.log(err);
    })
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.