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");
});
答案 0 :(得分:3)
You have to user data[0].username
because data
is an array containing a single value.
答案 1 :(得分:2)
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.
答案 2 :(得分:1)
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);
}
});
答案 3 :(得分:0)
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.