【发布时间】:2016-06-24 17:29:49
【问题描述】:
编辑 [已解决]:
我连接到错误的数据库...
我变了
var dbURI = 'mongodb://localhost/wifiplz'
到
var dbURI = 'mongodb://localhost/wifiPlz'
所以所有这一切都是由于一个错字(未大写的 p)。遇到此类问题的任何人请确保您连接到正确的数据库!
这是我的架构文件 (location.js):
var mongoose = require('mongoose');
var openingTimeSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var reviewSchema = new mongoose.Schema({
author: String,
rating: {type: Number, min: 0, max: 5, required: true},
createdOn: {type: Date, default: Date.now},
reviewText: String
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: {type: String, required: true},
rating: {type: Number, default: 0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index: '2dsphere'},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
// compiling schema as 'Location' model
mongoose.model('Location', locationSchema);
在我的路线中,我将路线映射到适当的控制器:
router.get('/locations/:locationId', locationsCtrl.locationRead);
在我的控制器 (locationsCtrl.js) 中,我尝试通过 id 查找位置:
var mongoose = require('mongoose');
var Location = mongoose.model('Location');
module.exports.locationRead = function(req, res) {
Location
.findById(req.params.locationId)
.exec(function(err, location) {
if (err) throw err;
res.status(200);
res.json(location); // returns null
});
}
当我对此进行测试时,我总是收到null 的有效 ID。将不胜感激一些关于为什么的见解。谢谢。
编辑:
使用mongo 和show collections 在我的计算机上检查集合的名称,我得到locations 作为集合名称。这正如预期的那样。虽然指定mongoose.model('Location', locationSchema, 'locations') 没有任何作用。
【问题讨论】:
-
你的猫鼬版本是什么?或添加
mongoose.set('debug', true);从日志中查看更多信息。 -
这是一个类似的问题列表,github.com/Automattic/mongoose/issues/3079,它可能会对您有所帮助。
-
10 美元表示这是您数据库中的现有集合,实际上称为
"location",而不是 mongoose 期望的复数"locations"。默认情况下,引用的集合是模型名称的“复数”。您可以通过mongoose.model("Location",locationSchema,"location")将集合名称指定为第三个参数来更改此设置。如果不是集合,那么您很可能连接到错误的数据库。如果这一切都失败了,console.log(req.params.locationId)以确保你实际上是在接受你的想法。这些是常见错误。 -
我电脑上的集合名称是
locations。我也用过mongoose.model(''Location', locationSchema, 'locations'),没有任何改变。
标签: javascript node.js mongodb express mongoose