NodeJS / MongoDB – 字段只添加一次?

我正在学习与Node(Express / Mongoose)和MongoDB的React,一切似乎现在按预期工作,但我有这个大问题:

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() } 

每次我POSTlogin和密码,它只被保存一次,然后结束。

所以例如,如果我发送POST三次:

login=admin&password=admin

login=admin2&password=admin2

login=admin3&password=admin3

db.users.count()显示1只有第一个POST (admin:admin)在数据库中。 其余的被忽略。 我正在运行console.logs,看看有什么不对,但每个POST获得不同的_id,但不知何故,不保存后的第一个。 我想也许有什么问题, save ,也许我应该使用updatecreate但每个教程,我已经看到和文档说,使用save

当我删除字段和收集是空的,然后发送POST立即保存,然后忽略其他所有POST(第二,第三等)。

我究竟做错了什么? 我想在我的collections中有超过1个用户:(

[编辑]

看起来我的ID正在“即时”创build,所以MongoDB应根据文档触发insert : https : //docs.mongodb.com/manual/reference/method/db.collection.save/#behavior (也是我的“我不知道它现在在做什么,因为它看起来不像update :/)

好的,我完全忘了我可以使用mongo的CLI进行debugging,问题很容易从那里发现。 如果发生这种情况,请尝试以下步骤:

启动mongo表单命令行/terminal。

尝试复制有问题的动作节点/mongoose处理你,在我的情况下,它是添加新的用户:

use users db.users.save( { login: "fromCLI", password: "fromCLI" } ) db.users.save( { login: "fromCLI2", password: "fromCLI2" } )

阅读错误信息,在我的情况是这样的:

"errmsg" : "E11000 duplicate key error collection: users.users index: username_1 dup key: { : null }"

我没有username索引。 我曾经有。 不得不放弃收集,然后神奇地开始工作!

你的问题是你有集合具有独特的索引,防止创build,所以只需删除该索引:

 db.users.dropIndex('index name here'); 

额外的build议:

1) db.on('error'不会捕获数据库操作错误。

2)总是尝试创造logging,然后回应。 在用户体验的情况下,如果帐户创build成功或不成功,用户必须被通知。

总之 – 检查这一个:

 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); }); }); });