【问题标题】:Issue with MongoDB, Node and Express-looking up ID in MongoMongoDB、Node 和 Express 在 Mongo 中查找 ID 的问题
【发布时间】:2016-11-13 21:43:27
【问题描述】:

我目前正在做一个简单的 MEAN 项目,我正在从我的 mongo db 中提取一个项目并将其显示在网页上。每当我去现场 http://localhost:3000/api/events/5782b1dbb530152d0940a227 看到关于对象的信息,我得到 null 显示。就像我说的,我想看到关于这个物体的信息。这是我的代码的样子:

控制器:

var mongoose = require('mongoose');
var Eve = mongoose.model('Info');

var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};

module.exports.eventsReadOne = function(req, res) {
 Eve
  .findById(req.params.eventid)
  .exec(function(err, info){
     sendJSONresponse(res, 200, info)
   });
  //sendJSONresponse(res, 200, {"status" : "success"});
 };

型号:

var mongoose = require( 'mongoose' )

var eventSchema = new mongoose.Schema({
  activity: String,
  address: String,
});

mongoose.model('Info', eventSchema);

路线:

var express = require('express');
var router = express.Router();
var ctrlEvents = require('../controllers/events');

//events
router.get('/events/:eventid', ctrlEvents.eventsReadOne);

module.exports = router;

现在,可能会注意到的一件事是我调用了我的 mongo 集合事件。但是,我忘记了事件是 JS 中的一个关键词,所以我尝试将其“更改”为 Info,您将在模型的最后一行看到它。就像我说的,如果我访问网站http://localhost:3000/api/events/5782b1dbb530152d0940a227,最后一个数字是 obj _id,那么我应该会看到上面的所有数据。相反,我看到的都是空的。任何帮助都会很棒,谢谢!

我的另一个模型文件 db.js 有连接:

var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/mission';
mongoose.connect(dbURI)

require('./events');

【问题讨论】:

  • 关心console.log(req.params) ?
  • 是的,似乎什么也没发生,我把它放在 sendJSONresponse 的正上方,有什么想法吗?
  • event 不是 JS 中的关键字。尝试添加一些错误处理。另外,我假设您在代码中的某处调用mongoose.connect()
  • 您需要检查控制台中的输出。只需检查 req.params 是否有任何值。
  • 我在另一个文件中调用 mongoose.connect(),添加到上面,我不确定 req.params 是否有值,因为我没有显示任何内容。

标签: node.js mongodb express


【解决方案1】:

Mongoose 将使用模型名称来确定它应该使用哪个 MongoDB 集合。默认方案是采用模型名称、小写和复数形式,并将结果用作集合名称,在您的情况下(使用 Info 作为模型名称)将是 infos

// This is where the model is created from the schema, and at this point
// the collection name is decided.
mongoose.model('Info', eventSchema);

如果您希望它使用不同的集合,您必须通过为您的架构设置 collection 选项来明确告诉 Mongoose 要使用哪个集合:

var eventSchema = new mongoose.Schema({
  activity : String,
  address  : String,
}, { collection : 'events' });

要修复您在 cmets 中陈述的错误(尚未为模型“任务”注册架构),您需要确保更改所有出现的 mongoose.model()

// To create the model:
mongoose.model('Mission', eventSchema);

// Later on, to access the created model from another part of your code:
var Eve = mongoose.model('Mission');

(虽然“任务”似乎是您的 数据库 的名称;因为您的集合称为 events 我认为模型名称 Event似乎更合适)

【讨论】:

  • 太棒了!你明白了,伙计!有用!感谢您帮助此人开始使用 MEAN Stack!
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 2021-08-22
  • 2017-09-15
  • 2011-09-03
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多