node.js - 当我发出获取请求时,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
}
路由器
路线allseries允许我访问所有内容。我想要做的是将该内容传递给SeriesModel,也许它在那里我遇到了数据没有正确插入的问题。
在路线series/:id是空值返回给我的地方
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);
解决方案
这是因为findById
像这样以对象的形式获取它的参数
SeriesModel.findById({_id:id})
您需要告诉查询要与传入对象匹配的 json 对象。
推荐阅读
- prestashop-1.7 - ClassNotFoundException - PrestaShop 1.7.4.3
- python - 比较两个数据帧之间的每个元素
- java - 随机生成器创建相同的数字
- java - 通过 Java SDK 的 Azure VM 指标
- pyspark - 在 Pyspark 中实现 K-medoids
- sql - 我在从多个表中删除行时遇到问题
- java - 如何将列表从jsp传递到servlet?
- swift - 如何通过 Swift 4.2 中的反射类类型使用 JSONDecoder 解码 JSON?
- azure - 如何在 Microsoft Azure 中配置 Web 服务应用程序的预热
- swift - 更新 Facebook SDK 问题