[英]Problems reading MongoDb collection with Node.js
I have problems reading this collection with mongoose and Node.js: 我在用猫鼬和Node.js读取此集合时遇到问题:
I have one JSON inside my Collection and i try to read this with this code: 我的收藏夹中有一个JSON,我尝试使用以下代码阅读:
materias.find().exec(function(err1,materias){
if(err1){console.log(err1); return next();}
for(x=0;x<materias.length;x++){
//console.log(materias[x].Nombre);
//var arreglo=materias[x].Horario[0].Dia; // TRY ONE
var arreglo=JSON.parse(materias[x].Horario[0]); // TRY TWO
console.log(arreglo[0]);
}
//RESPONSE TRY ONE
console.log(arreglo) UNDEFINED
//RESPONSE TRY TWO
undefined [
//if I use JSON.stringify the response is {[object][object]...
enter code here
You don't need to parse JSON
manually with mongoose. 您不需要使用mongoose手动解析
JSON
。
You get undefined
because you define variable arreglo
inside the loop but try to access it outside of it. 由于在循环内部定义了变量
arreglo
,但尝试在循环外部进行访问,因此undefined
。 This should work: 这应该工作:
materias.find().exec(function(err1,materias){
if(err1){console.log(err1); return next();}
for(x=0;x<materias.length;x++) {
var arreglo = materias[x].Horario[0]; // TRY TWO
console.log(arreglo);
}
What i suppose the error is: you have database named as materias and you are using the same name for the returned collection. 我想错误是:您有名为materias的数据库,并且对返回的集合使用相同的名称。 Try changing the return name collection to something other.
尝试将返回名称集合更改为其他名称。
materias.find().exec(function(err1, change_name_here ){ materias.find()。exec(function(err1, change_name_here ){
//required code //所需的代码
} }
FINALYYYYYYYYYY i fixed it changing my mongoose model I had this: FINALYYYYYYYYYY我修复了它,更改了我的猫鼬模型,我这样做是:
var materias=new Schema({
Nombre:{type:String, required:true},
Docente:{type:String, required:true},
Horario:{type:String, required:true}
});
module.exports = materias;
and change for this: 并为此更改:
Horario:[{Dia:String, Hora:String, Tiempo:String}]
for reading: 阅读:
for(x=0;x<materias.length;x++){
var arreglo=materias[x].Horario; // TRY TWO
console.log(arreglo[0].Dia);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.