【问题标题】:mongoose is querying another database猫鼬正在查询另一个数据库
【发布时间】:2020-04-16 01:32:24
【问题描述】:

编辑:添加图片集

edit2:经过几次调试,我尝试保存一个文档并运行 find() 查询,它成功了(我找到了我保存的测试文档)。我认为现在的问题在于与数据库的连接。我可能正在连接到其他地方

edit3 更改了标题,因为它似乎没有指向实际问题。
经过几次调试后,我发现 mongoose 正在查询我在 uri 中指定的数据库之外的其他地方。当我尝试保存测试文档时,它已成功保存,并且我能够使用 find() 将其取回。但是,当我使用 find() 时,它只返回了之前保存的测试文档。所以现在我想知道这些文件保存在哪里?
添加更多细节,这里是我写的一些代码:

apiServerRoutes.js

'use strict';
module.exports = function(app) {
  var apiServer = require('../controllers/apiServerControllers');

  app.route('/items')
    .get(apiServer.get_all_item);

  app.route('/items/:itemId')
    .get(apiServer.get_item);
};

apiServerControllers.js

'use strict';
var mongoose = require('mongoose');
var Item = mongoose.model('item_m');

exports.get_all_item = function(req, res) {
  console.log("get_all_item() is called");
  Item.find({}, function(err, item) {
    if (err)
      res.send(err);
    res.json(item);
  });
};

exports.get_item = function(req, res) {
  console.log("get_item() is called");
  Item.findOne({item_typeId: req.params.typeId}, '',function(err, item) {
    if (err)
      res.send(err);
    res.json(item);
  });
};

ItemSchema.js

'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = mongoose.Schema({
  item_name: String, 
  item_desc: String, 
  item_type: String,
});

var Item = mongoose.model('item_m', ItemSchema, 'item_m');
module.exports = Item;

server.js

var express = require('express'),
  app = express(),
  port = process.env.PORT || 3000,
  mongoose = require('mongoose'),
  Item = require('./api/models/ItemSchema'),
  bodyParser = require('body-parser');

mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.connect('mongodb+srv://[[user]]:[[pass]]@market-test-app-1dza9.mongodb.net/test?retryWrites=true&w=majority', {
  useNewUrlParser: true, useUnifiedTopology: true}); 

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connection Successful!");
});

var routes = require('./api/routes/apiServerRoutes');
routes(app);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.listen(port);
console.log('RESTful API server started on: ' + port);

编辑结束

下面的内容来自我在进行一些挖掘和调试之前提出的原始问题

所以我有这个控制器函数,它使用没有投影参数的简单查找查询

exports.get_all_item = function(req, res) {
  Item.find({}, function(err, item) {
    if (err)
      res.send(err);
    res.json(item);
  });
};

每次我在邮递员中运行我的请求时,我都会得到一个空结果。当我在 express 中打开调试模式时,我看到了 mongoose 发送的这个查询

Mongoose: item_m.find({}, { projection: {} })

当我尝试在 mongodb 中运行此查询时,我收到此错误

"message" : ">1 field in obj: {}",

如果我确实添加了投影参数,例如。 item_name,猫鼬发送这个:

Mongoose: item_m.find({}, { projection: { item_name: 1 } })

当在 mongodb 中运行该查询时,我收到此错误

"message" : "Unsupported projection option: projection: { item_name: 1.0 }",

但是当我将查询更改为

db.item_m.find({}, { item_name: 1 } )

它工作正常,返回我期望的结果。

对于 express、node.js 和 mongodb,我还是新手。这是 mongodb 和 mongoose 之间的一些版本问题吗? 我对 mongodb 使用 4.0.13,对 mongoose 使用 5.8.3,但根据我的研究,这应该没问题。我在这里还缺少什么?或者我应该检查哪些我可能错过的东西? 提前致谢。

【问题讨论】:

  • 请在项目查询前使用 async 和 await
  • Mongodb- 是一个数据库,而 mongoose- 是一个数据库查询库,它们并不相同。 mongoose 和 mongodb 的查询语法不同,因此请遵循文档。
  • @AnkitaKuchhadiya 是的,我知道它们不一样。我正在检查 mongoose 发送到 mongodb 的查询是否有效,显然它没有,或者有一些我不知道或错过的东西。

标签: node.js mongodb express mongoose


【解决方案1】:

我使用这种方法获取所有查询。我已根据您的需要对其进行了调整。

exports.get_all_item = (req, res, next) => {
  Item.find()
    .select("item_name")
    .exec()
    .then(items => {
      if (items.length > 0) {
        res.status(200).json(items);
      } else {
        res.status(204).json({
          message: "No items available"
        });
      }
    })
    .catch(error => {
      next(error);
    });
};

希望对你有帮助:)

【讨论】:

  • 返回 204,没有内容。
  • 您可以在帖子中编辑和添加您的收藏记录供我检查吗?
【解决方案2】:

当我使用 mongodb atlas 重新检查我的数据库时,我发现有两个现有数据库:master(我保存数据的地方)和 test(我不确定它是如何创建的,但它存在)。 mongoose 一直在访问 test 而不是 master。我将 URI 中的“test”更改为“master”,效果很好。

所以我想这里的教训是仔细检查 URI;并在调试时尝试保存示例数据并找到该数据的保存位置。

【讨论】:

    猜你喜欢
    • 2017-05-08
    • 2018-09-11
    • 2018-05-08
    • 2021-04-10
    • 2021-08-02
    • 2020-06-02
    • 2012-02-03
    • 2019-06-22
    • 2020-07-19
    相关资源
    最近更新 更多