【发布时间】:2017-02-21 23:57:31
【问题描述】:
在我的路线文件中,我有
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。
【问题讨论】:
-
在发送响应之前在服务器 console.log(user.name) 上。它在记录什么?
-
它记录未定义
-
我认为你应该调用方法toJSON
-
var json = user.toJSON(); res.send(json.name || '用户名未定义');这会导致错误。
-
由于它正在记录未定义的日志,因此将发送的唯一响应是“未定义用户名”。试试 console.log(user) - 你可能需要先 JSON.strinigfy(user),看看是否有 name 属性。
标签: json node.js mongodb mongoose mongoose-schema