首页 > 解决方案 > 当我发出获取请求时,model.findById 中的空值 [mongodb]

问题描述

问题 嗨,开发者,

我有一个问题,当我尝试通过 id 向系列发出获取请求时,它显示我为 null。

我从 Atlas Mongos 平台注意到我创建了该集合,但它没有向我显示数据,只有方案的结构向我显示

在此处输入图像描述

函数.js


const fs = require('fs');
const fetch = require('node-fetch');

const BASE_URL = " http://localhost:8081/api/v1/"

async function getSeries() {
  return new Promise((resolve , reject) =>{
    setTimeout(() => {
      const res =  require('./simple_database/series/1.json' , 'utf8');
      resolve(res)      
    }, 1000);
  })
}
module.exports = {
  getSeries
}

路由器

const express = require('express');
const router = express.Router();

const f = require('./function');
const SeriesModel = require('./models/series');

router.get('/allseries', (req, res) => {
  f.getSeries().then((series) =>{
    res.status(200).json({
      series
    })
  }).then((doc) =>{
    SeriesModel.insertMany(doc , function(err , docs){
      if(err){
        console.error(err)
      }else{
        console.log(docs);
        console.info('%d serie were successfully stored.', docs.length);
      }
    })
  })
});

router.get('/series/:id' , (req , res , next) =>{
  const id = req.params.id;
  SeriesModel.findById(id)
    .exec()
    .then((doc) =>{
      console.log("From database " , doc);
      res.status(200).json(doc)
    }).catch((err) =>{
      console.error(err);
      res.status(500).json({error: err})
    })
})

module.exports = router;

模型/series.js

const mongoose = require('mongoose');

const serieSchema = mongoose.Schema({
  "_id": {
    "$oid": {
      "type": "ObjectId"
    }
  },
  "series_id": {
    "type": "String"
  },
  "aggregateRating": {
    "reviewCount": {
      "type": "Number"
    },
    "ratingCount": {
      "type": "Number"
    },
    "@type": {
      "type": "String"
    },
    "ratingValue": {
      "type": "Number"
    }
  },
  "episodes": {
    "1x": {
      "07 Ghost": {
        "type": [
          "Mixed"
        ]
      }
    }
  },
  "metadata": {
    "description": {
      "type": "String"
    },
    "url": {
      "type": "String"
    },
    "image": {
      "type": "String"
    },
    "type": {
      "type": "String"
    },
    "id": {
      "type": "String"
    },
    "name": {
      "type": "String"
    }
  },
  "1x": {
    "07 Ghost": {
      "type": [
        "Mixed"
      ]
    }
  }
});

module.exports = mongoose.model("cr_series" , serieSchema);

标签: node.jsmongodbexpressmongoose

解决方案


这是因为findById像这样以对象的形式获取它的参数

SeriesModel.findById({_id:id})

您需要告诉查询要与传入对象匹配的 json 对象。


推荐阅读