在猫鼬中创建用户

Create User in mongoose

我的架构是:

var UserSchema = mongoose.Schema({
    name: {type:String},
    city: {type:String},
    accounts: [
        {
            typeA: [
                {
                    isUsed: String,
                    someInfo: String
                }
            ]
        },
        {
            typeB: [
                {
                    isUsed: String,
                    someInfo: String
                }
            ]
        }
    ]
});

我可以插入只有姓名和城市的文件。其中:

app.get('/createuser', function(req, res){
    var user = req.body;
    var name = req.body.name;
    var city = req.body.city;
    var type = req.body.type;

    User.create(user, function(err, doc){
        if(err) return err;
        else { res.send(doc); }
    }); 
});

我想在 accounts 中插入基于 var type = req.body.type; 的值。如果 type = typeA,我想要 typeA.isUsed = "yes" 的值 我试过了:

app.get('/createuser', function(req, res){
    var user = req.body;
    var name = req.body.name;
    var city = req.body.city;
    var type = req.body.type;

    if(type == "typeA"){

        user.accounts.typeA.isUser = "1";
        User.create(user, function(err, doc){
        if(err) return err;
        else { res.send(doc); }
    });
    }
    if(type == "typeB"){

        user.accounts.typeB.isUser = "1";
        User.create(user, function(err, doc){
        if(err) return err;
        else { res.send(doc); }
    }
});

但这不起作用。我怎样才能做到这一点?

非常感谢。

var userSchema = mongoose.Schema({
    name: String,
    city: String,
    email: String,
    accounts: {
        fbAccount:{
             foo: String,
             bar: String,
             baz: String
           },
          googleAccount:{
            foo: String,
            bar: String
           }
    }
});

好吧,这显然不是完美的,不会让你得到你想要的,但没有更多细节,这是我能做的最好的。

例如,您可以像这样访问 googleAccount...user.accounts.googleAccount.foo

希望对您有所帮助。

架构

var userSchema = mongoose.Schema({
    name: String,
    city: String,
    accounts: {
        typeA:{
             isUsed: Boolean,
                   .
        },
        typeB:{
             isUsed: Boolean,
                  .
        },           
    }
});  

route.js

var User = require('path/to/user);

app.get('/createuser', function(req, res){

    var user = new User();

    user.name = req.body.name;
    user.city = req.body.city;

    if(req.body.type == "typeA"){
        user.accounts.typeA.isUser = true;
    }
    if(type == "typeB"){
        user.accounts.typeB.isUser = true;
    }

    user.save(function(err, user){
        if(err) return err;
        res.send(user); 
    });
});

以上改编自我们的代码,但我认为更好的模式是每个用户的帐户数组:

accounts: [{
    email: String,
    type: String,
          .
    }],           
}

route.js

user.accounts.email = req.body.email;
user.accounts.type = req.body.type;