我正在Node.JS上的一个项目上,在那里我创建了一个用户模式,该用户模式具有一个名为interest的属性,其中包含String数组,同时为键分配请求值,interest密钥不采用请求属性。
POST路线:
app.post('/users', (req,res) => {
var user = new Users({
name : req.body.name,
email : req.body.email,
phone : req.body.phone,
designation : req.body.designation,
address : req.body.address,
intrests : req.body.intersts //Here I have added an array of String
});
user.save().then((userData) => {
res.status(200).send(userData);
}).catch((e) => {
res.status(400).send(e);
})
});
用户架构
var UserSchema = new Schema({
name : {
type : String,
required : true,
trim : true,
minlength : 5,
unique : true
},
email : {
type : String,
required : true,
trim : true,
minlength : 5,
validiate : {
validator : validator.isEmail,
message : 'Email is Valid'
}
},
phone : {
type : Number,
minlength : 10,
required : true
},
designation : {
type : String,
minlength : 4,
required : true
},
address : {
type: String,
required : true
},
intrests : {
type : Array,
default : [],
required : true
}
});
我已输入以下信息...
{
"name" : "Surya",
"email" : "suryanarayan88@outlook.com",
"phone" : "8895591782",
"designation" : "Java Developer",
"address" : "186/1783 Mahadev Nagar",
"intrests" : ["web developement","Games"]
}
我得到的结果是...
{
"_id": "5d031d27acc9840c7c3997a0",
"name": "Surya",
"email": "suryanarayan88@outlook.com",
"phone": 8895591782,
"designation": "Java Developer",
"address": "186/1783 Mahadev Nagar",
"intrests": [
null
],
"__v": 0
}
答案 0 :(得分:0)
您的架构存储数组或字符串错误
应该是
... // rest of schema code
address : { type: String, required : true},
intrests : {type: Array, required : true, default : [] }
由于您以前的interests
模式已经期望使用对象[{interest: []}]
的数组
而您正在传递["web developement","Games"]
字符串数组。
注意:根据您的评论, 这个。
interests : [{
type : String,
default : [],
required : true
}]
在您的模式中应该是这个。
intrests : {type: Array, required : true, default : [] }