【问题标题】:How to get record by object id in mongoose如何通过猫鼬中的对象ID获取记录
【发布时间】:2016-12-15 21:31:50
【问题描述】:

我想根据学生ID获取记录,我遵循以下方法,但即使数据存在,我也会使用它来清空。 我在数据库中的数据,

{
"_id" : ObjectId("58526f02b7258b0ec168ee77"),
"student" : ObjectId("58525c4c8cdabb7841b68163"),
"updated" : null,
"record_type" : "Invoice",
"created" : ISODate("2016-12-15T10:22:58.801Z"),
"__v" : 0

}

我的查询,

  exports.searchInvoiceByStudent = function (req, res) {
  var data = {},
  id = req.params.id,
  item = {'record_type':'Invoice','student':id};
  Invoice.find(item).exec(function (err, invoice) {
  if (err) {
    return err;
  }
  if (invoice.length > 0) {
    data = { status: 'success', error_code: 0, data: invoice };
  } else {
    data = { status: 'fail', error_code: 1, data: invoice };
  }
  res.jsonp({ 'details': invoice });
  });
};

但是我得到一个空数组,任何人都可以建议帮助。谢谢。

【问题讨论】:

  • 您能否编辑您的问题以包含Invoice 的架构定义?

标签: node.js mongoose meanjs


【解决方案1】:

你可以这样使用:

 exports.searchInvoiceByStudent = function (req, res) {
  var data = {},
  id = req.params.id,
  item = {'record_type':'Invoice','student':id};
  Invoice.find({student : id, record_type: 'Invoice}, function (err, invoice) {
  if (err) {
    return err;
  }
  if (invoice.length > 0) {
    data = { status: 'success', error_code: 0, data: invoice };
  } else {
    data = { status: 'fail', error_code: 1, data: invoice };
  }
  res.jsonp({ 'details': invoice });
  });

此版本使用直接回调(而不是 exec)。

或者如果你喜欢这个承诺(承诺由exec返回),你必须使用Promise#addBack(listener)添加你的查询结果监听器,这在你的代码示例中没有。

mongoose 文档提到了这个例子(对于 promise-case):

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 2013-10-02
    • 2017-06-05
    • 2014-03-10
    • 2017-04-29
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多