首页 > 解决方案 > 无法访问猫鼬模式属性

问题描述

所以...我基本上在数据库中搜索一个项目,找到它,打印它但我无法访问属性。当我尝试打印它们时,它们显示未定义。

我知道该属性实际上是未定义的,因为它不会破坏循环,而且我的猫鼬模式中确实有这两个属性。我还尝试将其字符串化并将其解析为 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 并且应该退出循环,但它没有。

这里没有任何帮助链接

标签: node.jsexpressmongoose

解决方案


好的,问题是 mongoose 将 .find() 函数的结果视为一个数组,我应该使用 results[0] 或使用 .findOne() 对其进行转换。我选择了前者。答案实际上在提供的链接中,但您必须滚动一下。告诉我你是否要我删除这个


推荐阅读