为什么 Mongoose 不允许我访问 JSON 属性?
Why is Mongoose not allowing me to access the JSON attributes?
在我的路线文件中,我有
router.get('/users/:user', function(req, res) {
mongoose.model('users').find({name: req.params.user}, function(err, user) {
res.send(user.name || 'User.name is not defined' );
});
});
我的架构定义为
var userDataSchema = new Schema({
name: String
}, {collection: 'users'});
mongoose.model('users', userDataSchema);
在我的路由文件中,如果我只执行 res.send(user)
,那么它会返回正确的 JSON 以及所有用户的姓名。我的问题是我无法从 JSON 访问特定名称。
我已经尝试对那个变量执行 JSON.stringify(user)
然后 JSON.parse()
,但是 user.name 仍然无法访问。我现在也尝试了 user.toJSON()
,但这会导致错误,甚至不会响应 'User.name is not defined'
编辑:这是 JSON:
[
{
_id: "57feb97017910fa7e0e194d8",
name: "Garrett"
},
{
_id: "57feb97817910fa7e0e194d9",
name: "Steve"
},
{
_id: "57feb97c17910fa7e0e194da",
name: "Joe"
}
]
所以当我转到 /users/Steve 和 console.log(user)
时,它会为该用户记录正确的 JSON。
使用 .findOne 或用户对象将是数组
在我的路线文件中,我有
router.get('/users/:user', function(req, res) {
mongoose.model('users').find({name: req.params.user}, function(err, user) {
res.send(user.name || 'User.name is not defined' );
});
});
我的架构定义为
var userDataSchema = new Schema({
name: String
}, {collection: 'users'});
mongoose.model('users', userDataSchema);
在我的路由文件中,如果我只执行 res.send(user)
,那么它会返回正确的 JSON 以及所有用户的姓名。我的问题是我无法从 JSON 访问特定名称。
我已经尝试对那个变量执行 JSON.stringify(user)
然后 JSON.parse()
,但是 user.name 仍然无法访问。我现在也尝试了 user.toJSON()
,但这会导致错误,甚至不会响应 'User.name is not defined'
编辑:这是 JSON:
[
{
_id: "57feb97017910fa7e0e194d8",
name: "Garrett"
},
{
_id: "57feb97817910fa7e0e194d9",
name: "Steve"
},
{
_id: "57feb97c17910fa7e0e194da",
name: "Joe"
}
]
所以当我转到 /users/Steve 和 console.log(user)
时,它会为该用户记录正确的 JSON。
使用 .findOne 或用户对象将是数组