Как сделать запрос в Mongodb на основе конкретных данных?

0

У меня есть следующие схемы в Mongodb:

Схема проблемы:

'use strict';

// modules dependencies
var mongoose = require('mongoose'),
    Schema   = mongoose.Schema;

// model
var ProblemSchema = new Schema({

  description: {
    type     : String,
    unique   : false,
    required : false
  },
  creator: {
    type     : Schema.Types.ObjectId,
    unique   : false,
    required : true,
    ref      : 'User'
  },
  idea: {
    type     : Schema.Types.ObjectId,
    unique   : false,
    required : true,
    ref      : 'Idea'
  }
});

mongoose.model('Problem', ProblemSchema);

И схема идеи:

'use strict';

// modules dependencies
var mongoose = require('mongoose'),
    Schema   = mongoose.Schema;

// model
var IdeaSchema = new Schema({
  name: {
    type     : String,
    unique   : true,
    required : true
  },
  description: {
    type     : String,
    unique   : false,
    required : false
  },
  creator: {
    type     : Schema.Types.ObjectId,
    unique   : false,
    required : true,
    ref      : 'User'
  },
  image : String
});

mongoose.model('Idea', IdeaSchema);

В поддержке я имею следующее:

exports.getById = function (req, res) {
     Problem.findById({idea:req.params.id}, function (err, problem) {
        if (err) return res.status(400).send(err)

        if (problem) {
          res.send(problem);
        } else {
          res.status(404).send('Problem not found')
        }
      });
    };

Я пытаюсь запросить проблемы на основе Idea id, но это не работает, и я получаю следующую ошибку: GET http://localhost: 3001/api/problems/5698ee90d62061f40bb00a7d 400 (Bad Request) Я новичок в angularjs и nodejs, надеюсь, кто-нибудь может мне помочь?

2 ответа

0

Попробуйте использовать findOne вместо findById?

exports.getById = function (req, res) {
 Problem.findOne({idea:req.params.id}, function (err, problem) {
    if (err) return res.status(400).send(err)

    if (problem) {
      res.send(problem);
    } else {
      res.status(404).send('Problem not found')
    }
  });
};
0

Функция findById означает findById одного документа по его полю _id. findById (id) почти эквивалентен findOne({ _id: id }). замените его на findOne следующим образом:

exports.getById = function (req, res) {
 Problem.findOne({idea:req.params.id}, function (err, problem) {
    if (err) return res.status(400).send(err)

    if (problem) {
      res.send(problem);
    } else {
      res.status(404).send('Problem not found')
    }
  });
};

Ещё вопросы

Сообщество Overcoder
Наверх
Меню