本文介绍了猫鼬'findById'返回带有有效ID的null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑[已解决]:

我连接到错误的数据库...

I was connecting to the wrong database...

我改变了

var dbURI = 'mongodb://localhost/wifiplz'

var dbURI = 'mongodb://localhost/wifiPlz'

所以所有这些都是由于错字(大写的p)造成的.遇到此类问题的任何人都请确保您连接到正确的数据库!

so all of this was due to a typo (uncapitalized p). Anyone with this type of problem make sure you are connecting to the right database!

这是我的架构文件(location.js):

Here is my schema file (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);

在我的路线中,我将路线映射到适当的控制器:

In my routes, I map the route to appropriate controller:

router.get('/locations/:locationId', locationsCtrl.locationRead);

在我的控制器(locationsCtrl.js)中,我尝试通过ID查找位置:

In my controller (locationsCtrl.js) I try to find a location by 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.希望对原因有所了解.谢谢.

When I tested this, I am always getting null for valid ids. Would appreciate some insight as to why. Thanks.

使用mongoshow collections在计算机上检查集合的名称,我得到locations作为集合名称.这是预期的.尽管指定mongoose.model('Location', locationSchema, 'locations')无效.

Checking for the name of the collection on my computer using mongo and show collections, I get locations as the collection name. This is as expected. Although specifying mongoose.model('Location', locationSchema, 'locations') doesn't have any effect.

推荐答案

亲爱的

进行以下更改:

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字段,但请确保该字段本质上应该是主字段或唯一字段.如果不是在该字段上创建索引

感谢&干杯

这篇关于猫鼬'findById'返回带有有效ID的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:33