[英]Error while saving data in MongoDB atlas with mongoose
I'm trying to save data in the MongoDB atlas with node.js and mongoose.我正在尝试使用 node.js 和 mongoose 将数据保存在 MongoDB 图集中。
Every time I use MySchema.save()
, Data is inserting But I'm also getting the error:每次我使用
MySchema.save()
,数据都在插入但我也收到错误:
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;
I know it was asked 2 months ago, but for those who will encounter the same issue.我知道 2 个月前有人问过,但对于那些会遇到同样问题的人。 You are mistakenly entering a wrong char at the end of the URI string:
您错误地在 URI 字符串的末尾输入了错误的字符:
mongodb+srv://${ user }:${ password }@track-mkahl.mongodb.net/test?retryWrites=true&w=majority;
You need to delete the ;
您需要删除
;
after the word majority
.在词
majority
。
This helped me.这对我有帮助。
const schema = new Schema({ name: String }, { writeConcern: { w: 'majority', j: true, wtimeout: 1000 } });
https://mongoosejs.com/docs/guide.html#writeConcern https://mongoosejs.com/docs/guide.html#writeConcern
"mongoURI" : "mongodb+srv://${ user }:${ password }@cluster0.mde0j.mongodb.net/cluster0?retryWrites=true&w=majority "
我在 default.json 中遇到了同样的错误,它的简单错误只是在最后删除&w=majority
部分,它将被解决
对我来说,它也在 URI 字符串中,就像@Yossi Saadi 所建议的那样,只是我在那里写了majoritys
而不是majority
I think there's something wrong with this line.我认为这条线有问题。
let User = require('../models/users.models');
let User = require('../models/users.models');
I have created a solution for you.我已经为您创建了一个解决方案。
/models/user.js
/模型/用户.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect("mongodb://localhost/stack-overflow", { useNewUrlParser: true })
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
/routes/userroute.js
/routes/userroute.js
const User = require("../models/user")
// Imagine run() as an asynchronous request handler
async function run() {
try {
const user1 = new User({ username: "lidafafnus" })
user1.save((err,result) => {
console.log(err, result)
})
} catch(error) {
console.log(error)
}
}
run()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.