为什么Mongoose不允许我访问JSON属性?

时间:2021-09-24 02:35:16

In my routes file, I have

在我的路线文件中,我有

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' );
  });
});

And my schema is defined as

我的架构定义为

var userDataSchema = new Schema({
  name: String
}, {collection: 'users'});

mongoose.model('users', userDataSchema);

In my routes file, if I just do res.send(user), then it gives me the proper JSON back with all of the users with their names. My problem is that I am not able to access the specific name from the JSON.

在我的路由文件中,如果我只是执行res.send(user),那么它会向我提供适当的JSON,并返回所有具有其名称的用户。我的问题是我无法从JSON访问特定名称。

I have tried doing JSON.stringify(user) and then JSON.parse() to that variable, but user.name is still not accessible. I have now also tried user.toJSON(), but this causes an error and does not even respond with 'User.name is not defined'

我已经尝试对该变量执行JSON.stringify(user)和JSON.parse(),但仍然无法访问user.name。我现在也尝试过user.toJSON(),但这会导致错误,甚至不会回复“User.name未定义”

EDIT: Here is the JSON:

编辑:这是JSON:

[
  {
    _id: "57feb97017910fa7e0e194d8",
    name: "Garrett"
  },
  {
    _id: "57feb97817910fa7e0e194d9",
    name: "Steve"
  },
  {
    _id: "57feb97c17910fa7e0e194da",
    name: "Joe"
  }
]    

So when I go to /users/Steve and console.log(user), it logs the correct JSON for that user.

因此,当我转到/ users / Steve和console.log(用户)时,它会为该用户记录正确的JSON。

1 个解决方案

#1


1  

use .findOne or user object will be array

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

#1


1  

use .findOne or user object will be array

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