问题描述
所以我正在开发我的登录系统,使用 Mongo 作为我的后端。我希望能够在一个帐户上拥有多个用户,因此我正在开发一种方法来处理此问题。我有我的帐户模型和我的用户模式。这就是我当前尝试创建用户的方式:
router.post('/createuser',async(req,res) =>{
try{
const acc = await Account.findOne({"Email": req.body.Email});
if(!acc) throw Error('Email not found');
var newUser = new User(req.body.User);
acc.Users.push(newUser);
res.status(200).send({success:true});
}
catch(err){
res.status(400).send({msg:err.toString(),success:false});
}
});
这是我的用户架构:
const UserSchema = new Schema({
// Name of the user
Username:{
type:String,required:true,unique:true
},// PIN for each user
PIN:{
type:Number,require:true
}
});
module.exports = UserSchema;
我的帐户模型:
const User = require('../Models/UserData');
const AccountSchema = new Schema({
// Email linked to this account
Email:{
type:String,unique:true,index:true
},// Password for the account
Password:{
type : String,required : true
},// Users on this account
Users:{
type:[User],required:true
}
});
module.exports = mongoose.model('Account',AccountSchema);
它返回 success:true
,但我在数据库中看到的唯一变化是一个全新的完全空的集合。我还需要检查用户名是否已经存在,但一次一个。
编辑:这是我用于 POST 请求的正文:
{
"Email":"Paul@test.com","User":
{
"Username":"56","PIN":4659
}
}
解决方法
将更新的记录保存到数据库 function foo() {
$('#bar > table > tbody > tr').each(function () {
$(this).find('td:nth-child(3)').text() == '1' && $(this).find('td:nth-child(1)').css('background-color','green');
$(this).find('td:nth-child(3)').text() == '2' && $(this).find('td:nth-child(1)').css('background-color','yellow');
$(this).find('td:nth-child(3)').text() == '3' && $(this).find('td:nth-child(1)').css('background-color','red');
});
}
如果您想将记录保存到用户模型并调用 acc.save
user.save