【问题标题】:Why is Mongoose not allowing me to access the JSON attributes?为什么 Mongoose 不允许我访问 JSON 属性?
【发布时间】: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


【解决方案1】:

使用 .findOne 或用户对象将是数组

【讨论】:

  • 好的,成功了。虽然用户对象是一个数组,但这很奇怪。当我做typeof user 它说object
  • 那么它是否返回一个数组,因为它不知道会有多少名称?所以基于此,如果你特别说 .find().limit(1) 那么它就会知道只有一个名字可以给出。
  • 数组是javascript中的对象,需要测试Array.isArray(user)
  • .find 总是返回数组,For findOne() it is a potentially-null single document, find() a list of documents, - mongoosejs.com/docs/queries.html
  • 通常情况下,该用户变量应命名为users,以便更清楚。
猜你喜欢
  • 2014-10-17
  • 2020-03-12
  • 2020-11-24
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
相关资源
最近更新 更多