我正在尝试将记录添加到我的mongodb数据库中。我确信我提供的是正确的值,尽管猫鼬正在考虑丢失它们。这是我的架构 -
var mongoose = require('mongoose');
var SocketUserSchema = new mongoose.Schema({
name: String,
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
devices: [{
name: String,
platform: String
}],
first_ip: {
type: String,
default: "0.0.0.0"
},
last_login_ip: {
type: String,
default: "0.0.0.0"
},
added_at: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('SocketUser', SocketUserSchema);
这是我的创建代码段 -
console.log('registered triggered ' + data);
/*var jsonData = data;
jsonData.first_ip = clientIpAddress;
jsonData.last_login_ip = clientIpAddress;*/
var user = new SocketUser({
username: data.username,
password: data.password,
devices: data.devices,
first_ip: clientIpAddress,
last_login_ip: clientIpAddress
});
SocketUser.create(user, function(err, post) {
if (err) {
console.log('error',err);
} else {
console.log('success');
}
});
这是我发送的示例用户数据 -
{
"username": "nexus",
"password": "noob",
"devices": [
{
"name": "Nexus",
"platform": "android"
}
]
}
这是我得到的错误 -
{
"message": "SocketUser validation failed",
"name": "ValidationError",
"errors": {
"username": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "username"
},
"message": "Path `username` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "username"
},
"password": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "password"
},
"message": "Path `password` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "password"
}
}
}
正如您所看到的,用户名和密码这两个字段都存在于数据中,但它仍然给出了错误。我已经尝试将数据json直接发送到Create方法,也尝试了save方法。两者都给出了相同的错这里有什么我想念的吗?
更新
我尝试验证该记录,然后将其添加到数据库并且它给出了相同的错误 -
user.validate(function(err) {
if (err) {
console.log("error "+err.message+"\nFull error: "+JSON.stringify(err));
}
else {
}
});
registered triggered {"username":"nexus","password":"noob","devices":[{"name":"N
exus","platform":"android"}]}
error SocketUser validation failed
Full error: {"message":"SocketUser validation failed","name":"ValidationError","
errors":{"password":{"properties":{"type":"required","message":"Path `{PATH}` is
required.","path":"password"},"message":"Path `password` is required.","name":"
ValidatorError","kind":"required","path":"password"},"username":{"properties":{"
type":"required","message":"Path `{PATH}` is required.","path":"username"},"mess
age":"Path `username` is required.","name":"ValidatorError","kind":"required","p
ath":"username"}}}
我无法找到用户名和密码的问题。出于显而易见的原因,我希望这些字段成为必填字段。
答案 0 :(得分:2)
我发现了这个问题,我检查了我是否正确获取了data.username和data.password。它们导致__del__
。然后我意识到数据实际上是一个字符串,而不是一个对象。所以我把它解析成json,然后我就把它弄好了。这是代码,以防有人陷入同样的问题 -
undefined