我的架构是:
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/