【发布时间】:2021-10-01 07:31:06
【问题描述】:
所以...我基本上在数据库中搜索一个项目,找到它,打印它但我无法访问属性。当我尝试打印它们时,它们显示未定义。
我知道该属性实际上是未定义的,因为它不会破坏循环,而且我的猫鼬模式中确实有这两个属性。我还尝试将其字符串化并将其解析为 json,但没有成功。 (这是我能找到的所有材料)
这是脚本:
const name_to_find = 'Copac';
async function myFetch(){
const express = require('express');
const mongoose = require('mongoose');
const Item = require('./models/Item');
const mongoUrl = process.env.MONGO_URL;
const appsc = express();
var connectWithRetry = function() {
return mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function(err) {
if (err) {
console.error('Failed to connect to mongo on startup - retrying in 3 sec', err);
setTimeout(connectWithRetry, 3000);
}
});
};
connectWithRetry();
var date1 = new Date();
while(true){
var date2 = new Date();
if(date1.getTime() - date2.getTime() > 100000)
break;
try {
const response = await Item.find({name: name_to_find});
var mergi = JSON.parse(JSON.stringify(response));// doesn t work
//if (response['status'] == 1)
if(response.status == 1){
console.log("200");
break;
}
else {
console.log(JSON.stringify(response));
console.log(response.status);
console.log(mergi.name);
}
}
catch (err) {
console.error(err);
console.log(name_to_find);
}
}
}
myFetch();
这是架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ItemSchema = new Schema({
status: {
type: Number,
required: true
},
name: {
type: String,
required: true
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
这是输出:
[{"_id":"60fc235414d05a001a5fa630","status":1,"name":"Copac","__v":0}] 未定义未定义
如你所见,它确实是 1,应该退出循环,但它没有。
link 没有任何帮助。
【问题讨论】: