【问题标题】:mongoose 'findById' returns null with valid idmongoose 'findById' 返回具有有效 id 的 null
【发布时间】: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。将不胜感激一些关于为什么的见解。谢谢。

编辑:

使用mongoshow 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


【解决方案1】:

亲爱的

进行以下更改:

var mongoose = require('mongoose');
var Location = mongoose.model('Location');

module.exports.locationRead = function(req, res) {
  Location
    .findOne({_id: req.params.locationId}, function (err, location){
      if (err) throw err;
      res.status(200);
      res.json(location); // returns null
    });
}

_id 可以是您的任何字段,因此请用 _id 替换您的 db 字段,但请确保该字段本质上应该是主要的或唯一的。如果不是在该字段上创建索引

感谢和欢呼

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2021-02-05
    • 2020-09-09
    • 2016-04-19
    • 2020-11-19
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多