node.js - 在 Mongoose 中创建用户

标签 node.js mongodb mongoose mongoose-schema

我的架构是:

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

我想根据 var type = req.body.type; 将值插入到 accounts 中。如果 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

我希望这有帮助。

关于node.js - 在 Mongoose 中创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940463/

相关文章:

javascript - 如何使用环回自关系实现递归连接?

node.js - Passport Facebook 验证未调用回调

node.js - 使用 Mongoose 查找所有文件

MongoDB 映射减少。 $存在于嵌套字段

mongodb - 条件 Mongoose 查询

android - 如何使用 Node.js FCM 将通知发送到特定包名称

javascript - Chrome 调试协议(protocol) : Create local storage value

mongodb - Go Lang 和 Labix mgo - 在后续请求后获取 EOF

javascript - 在 MongooseJs 中选择特定字段

javascript - Mongoose TypeScript ObjectId 转换 - 类型 'string' 不可分配给类型 'Condition<ObjectId | undefined>'