I'm learning React with Node (Express/Mongoose) and MongoDB and everything seems to work as expected now but I have this huge issue:
var userSchema = new mongoose.Schema({
login: { type: String, required: true, unique: true },
password: { type: String, required: true }
})
app.post('/registerUser', function (req, res) {
res.send(req.body)
db.on('error', console.error.bind(console, 'connection error:'))
// save user using model
var user = new UserModel(req.body)
user.save()
}
Every time I POST login and password it gets saved only once and then it's over.
So for example if I send POST three times:
login=admin&password=admin
login=admin2&password=admin2
login=admin3&password=admin3
db.users.count()
shows 1
and only the very first POST (admin:admin) is in the database. The rest is being ignored. I'm running console.logs to see what's wrong but every POST gets different _id, but somehow then do not save after the first one. I was thinking maybe there is something wrong with save
and maybe I should use something like update
or create
but every tutorial I've seen and the documentation says to use save
.
When I remove the field and the collection is empty and then send POST it saves immediately and then ignores every other POST (second, third, etc.).
What am I doing wrong? I want to have more than 1 user in my collection :(
[EDIT]
Looks like my ID is being created "on the fly" so MongoDB should trigger insert
according to the docs: https://docs.mongodb.com/manual/reference/method/db.collection.save/#behavior (also I'm not sure what it's doing right now, because it doesn't look like update
either :/)
Your problem is You've collection that has unique index that prevents creation, so just remove that index:
db.users.dropIndex('index name here');
Extra advice:
1) db.on('error'
will not catch db operation errors.
2) Always try to create record, then respond. In case of user experience user must be informed if account created successfully or not.
In short - check this one:
db.on('error', console.error.bind(console, 'connection error:'))
app.post('/registerUser', (req, res) => {
// 1. check if user account exist
const
query = {
login: req.body.login
};
UserModel
.findOne(query)
.exec((error, user) => {
if(error) {
console.error('ERROR:', error);
res.status(500).send({
type: 'system',
message: 'Cannot create user record',
trace: error
});
return;
}
if(user) {
res.status(405).send({
type: 'not-allowed',
message: 'User record already exists'
});
return;
}
// 2. create record if user account record does not exist
UserModel.create(req.body, (error, user) => {
if(error) {
console.error('ERROR:', error);
res.status(500).send({
type: 'system',
message: 'Cannot create user record',
trace: error
});
return;
}
res.send(user);
});
});
});
OK, I totally forgot I could debug it using mongo's CLI, the problem was quite easy to spot from there. If this happens to you try these steps:
Start mongo form command line / terminal.
Try replicating the problematic action node/mongoose handles for you, in my case it was adding new users:
use users
db.users.save( { login: "fromCLI", password: "fromCLI" } )
db.users.save( { login: "fromCLI2", password: "fromCLI2" } )
Read the error message, in my case it was:
"errmsg" : "E11000 duplicate key error collection: users.users index: username_1 dup key: { : null }"
I do not have username
index. I used to have. Had to drop the collection and then it magically started to work!