简体   繁体   中英

Undefined returned from object

In the below code, when i try to console log the data object it returns a correct username and password as below.

[ { _id: 5b7d6366db5064296cbeb79c,
    username: 'ajith',
    password: 'sdf2343@3e!',
    __v: 0 } ]

But the console log of the data.username returns undefined. Why this is happening? why it is not returning the value ?

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended:true}));

mongoose.connect
("mongodb://<user>:<pass>@ds129762.mlab.com:29762/<dbnmae>")

var userSchema = new mongoose.Schema({
     username : String,
     password : String
});

var User = mongoose.model("User",userSchema);

app.get("/",function(req,res){
   User.find({"username": "ajith"},function(err,data){
      if(err){
         console.log(err);
      }else{
        console.log(data);
        console.log(data.password+" "+data._id);
      }
    });
});


app.listen(3000,function(){
    console.log("server started and listening at the port 3000");
});

您必须使用data[0].username因为data是一个包含单个值的数组。

User.find() will return you a array result. Thus, you need to use findOne() query.

User.findOne({"username": "ajith"},function(err,data){
   if(err){
       console.log(err);
   }else{
     console.log(data);
     console.log(data.password+" "+data._id);
   }
});

If you have unique username property for all the documents then it is always recommended to use findOne() query for unique query combination instead of using find() which returns a array as you are expecting a single document from the mongoose query. This is also advantageous when you write test cases for the same code as you can assert a object response instead of array response.

It's not returning anything, since data is an array. If you want to access the first element of that array only, use

console.log(data[0].password+" "+data[0]._id);

Or, if you want to view all elements, use a loop:

data.forEach(d => console.log(d.password+" "+d._id);

If you are only expecting one document to be returned from MongoDB, use Model#findOne :

User.findOne({
  "username": "ajith"
}, function(err, user) {
  if (err) {
    console.log(err);
  } else {
    console.log(user);
    console.log(user.password + " " + user._id);
  }
});

That usually happens when you have no defined dedicated type for the output but an object, array or so (generally it is a root object with no fields). So, in your case, it is returning an object itself and then shows you what's inside but you cannot call its fields because your app knows nothing about them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM