我试图使用MongoDB查询_id
的单个文档。我使用的是猫鼬(版本: 4.11.1)。当我尝试运行查询时,我将_id
作为localhost:3000/poi/one/595ef9c8c4891179f8b4bbfb
路由上的URL传递。
当我点击enter时,浏览器将继续加载,永远不会完成。我能够在控制台中看到“获取一个POI”。但再也见不到其他东西了。
我正在使用mLab托管我的DB。里面只有一份文件。
mLab文档:
这里是我的查询代码:
let express = require('express');
let router = express.Router();
let {Poi} = require('../models/db-model');
router.get('/one/:id', (req, res, next) => {
console.log('getting one POI');
Poi.findOne({_id: req.params.id}).exec(function (err, poi) {
if (err) {
res.send('error occurred')
}
else {
console.log(poi);
res.send(poi)
}
});
});
My数据库模型:
const mongoose = require('mongoose');
// point of interest schema
let poiSchema = mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
trim: true,
},
url: {
type: String,
required: true
},
address: {
type: String,
required: true
},
cost: {
type: Number,
required: false
}
});
// instantiate models
let Poi = mongoose.model('Poi', poiSchema);
// export models
module.exports = {Poi};
我已经困在这个问题上好几个小时了,根本搞不清是什么问题。
编辑:
猫鼬配置:
const mongoose = require('mongoose');
const config = require('../app-config.json');
mongoose.Promise = global.Promise;
// connect to mLab Collection
mongoose.connect(config.dbUri);
module.exports = {mongoose};
发布于 2017-07-07 17:51:29
在findOne
的官方文档中,Mongoose建议在通过_id
字段查询时使用Model.findById()
方法。您可以在这里专门阅读findById
的文档:Model.findById
从本质上说,它看起来应该是:
Poi.findById(req.params.id).exec(function (err, poi) {
// ...
发布于 2017-07-09 18:09:59
你问题的答案很简单。
虽然req.params.id
是一个String
,但它并不等于mongo生成的ID。为了按id查询,您必须将String
转换为ObjectId
,这可以通过多种方式完成。
如果模块中需要mongoose
,则只需通过to:mongoose.Types.ObjectId(req.params.id)
将字符串转换为对象id,然后将id作为对象而不是字符串,就可以成功地进行查询。
https://stackoverflow.com/questions/44981708
复制