I'm trying to save data in the MongoDB atlas with node.js and mongoose.
Every time I use MySchema.save()
, Data is inserting But I'm also getting the error:
UnhandledPromiseRejectionWarning: MongoWriteConcernError: No write concern mode named 'majority;' found in replica set configuration
Also, there is no duplicate entry, Data is also inserting But I'm also getting the error
let User = require('../models/users.models');
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('user added!'))
.catch(err => res.status(400).json('Error: ' + err));
User model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
},
{
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Mongoose can be used to connect to both MongoDB and MongoDB Atlas to your Node. js app.
yes you should, its a good practice. Mongoose requires a connection to a MongoDB database. You can use require() and connect to a locally hosted database with mongoose.
When we run code to save or update the data, all validator runs and if any issue is found by the validator, mongoose throws the error. But these errors are completely different, different validators send errors in different ways.
for traditional SQL databases. The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer. In addition to enforcing a schema, Mongoose also offers a variety of hooks, model validation, and other features aimed at making it easier to work with MongoDB.
I know it was asked 2 months ago, but for those who will encounter the same issue.
You are mistakenly entering a wrong char at the end of the URI string: mongodb+srv://${ user }:${ password }@track-mkahl.mongodb.net/test?retryWrites=true&w=majority;
You need to delete the ;
after the word majority
.
This helped me.
const schema = new Schema({ name: String }, {
writeConcern: {
w: 'majority',
j: true,
wtimeout: 1000
}
});
https://mongoosejs.com/docs/guide.html#writeConcern
"mongoURI" : "mongodb+srv://${ user }:${ password }@cluster0.mde0j.mongodb.net/cluster0?retryWrites=true&w=majority "
I get the same error with this in default.json its simple error just delete the &w=majority
part at the end and it will be solved
for me it was also in the URI string like @Yossi Saadi has suggested, it's just that I had majoritys
written there instead of majority
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With