[英]Can't access JSON value from data fetched from MongoDB
Goodmorning, I have the oddest thing. 早上好,我有最奇怪的事情。 I hope someone can help me with this.
我希望有人可以帮助我。
I'm fetching data from MongoDB (via Mongoose) Very simple result 我正在从MongoDB中获取数据(通过Mongoose)非常简单的结果
{
reqts: 1469468008496
}
I am trying to access the property reqts
It's however undefined. 我正在尝试访问属性
reqts
,但是它是未定义的。 But the result above is very clear about it's existence. 但是上面的结果非常清楚它的存在。
What I am doing is the following 我在做什么是以下
// This gives me the above result, but doing data.reqts gives me nothing.
Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, item) {
var data = item
response.json(data)
});
This gives me the object I mentioned before. 这给了我前面提到的对象。 If I do:
如果我做:
var data = item.reqts
It gives me nothing in return (response is empty). 它没有给我任何回报(响应为空)。
Hope someone can help me with this. 希望有人可以帮助我。 Thanks!
谢谢!
UPDATED: I am now writing out to console too. 更新:我现在也写到控制台。
Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
if (err) { response.status(500).json({error: err}) }
else {
console.log(typeof data)
console.log(data)
console.log(data.reqts)
response.json(data)}
});
This is what it writes to console. 这就是它写入控制台的内容。
object
{ reqts: 1469468008496 }
undefined
UPDATED: 更新:
This seems to explain it: Dot operator not fetching child properties of a Mongoose Document object 这似乎可以解释这一点: 点运算符未获取Mongoose Document对象的子属性
Well as you already said - you forgot to define scheme. 就像您已经说过的-您忘记了定义方案。 So next code is working
所以下一个代码正在工作
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/so');
var Couple = mongoose.model('Couple', { reqts: Number });
var couple = new Couple({ reqts: 1469468008496 });
couple.save(function (err) {
if (err) {
console.log(err);
} else {
Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
console.log(data.reqts);
});
}
});
But I must say there is a way around this problem. 但是我必须说有解决此问题的方法。 You can access field undefinied in model with
data._doc
so next code would work too: 您可以使用
data._doc
访问模型中data._doc
字段,因此下一个代码也可以工作:
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/so');
var treet = require('treet');
var Couple = mongoose.model('Couple', {ts: Number}); // no reqts, we even can use {}
Couple.findOne().sort('-reqts').select('reqts -_id').exec(function(err, data) {
console.log(data._doc.reqts);
});
I think undefined fields hiding is made to make simpler sending document right to the output without additional selection of required fields. 我认为隐藏未定义的字段是为了使向输出发送文档更加简单,而无需额外选择必填字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.