简体   繁体   中英

mongoose is querying another database

edit : added image of collection

edit2 : after a few debugging, i tried to save a document and run the find() query, and it worked (i found the test document i saved). i think the problem now is somewhere in the connection to the db. i may be connecting to somewhere else

edit3 changed title because it doesnt seem to point to the actual problem.
after a few debugging, i found out that mongoose is querying to somewhere else aside from the database i specified in uri. when i tried to save a test document, it was saved successfully and i was able to get it back using find(). However when i used find(), it only returned the previously saved test document. So now im wondering where are these documents saved?
to add more details, here are some of the codes ive written:

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);

end of edit3

the stuff below this are from the original question i had before i did some digging and debugging

So I have this controller function which uses a simple find query with no projection parameters

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

Everytime I run my request in postman, I get an empty result. When I turned debug mode on in express, I saw this query sent by mongoose

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

When I try to run this query in mongodb, i get this error

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

If I do add a parameter for projection eg. item_name, mongoose sends this:

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

and when run that query in mongodb, i get this error

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

But when I change the query to

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

It works fine, returning the results that Im expecting.

Im still new to both express, node.js, and mongodb. Is this some version problem between mongodb and mongoose? Im using 4.0.13 for mongodb and 5.8.3 for mongoose but from what I researched, this should be fine. What other stuff am I missing here? Or what ever stuff should I check into that I may have missed? Thanks in advance.

收藏图片

I use fetch all query using this method. I have tweaked it for your need.

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);
    });
};

Hope it helps :)

When I checked back in my DB using mongodb atlas, I found that there were two existing databases: master (where I keep my data) and test (im not sure how this was created, but it existed). The entire time mongoose was accessing test and not master. I changed the 'test' in my URI to 'master' and it worked fine.

So I guess the lesson here is to double check the URI; and when debugging, try saving a sample data and find where that data is saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM