【问题标题】:Sails.js Waterline native MongoDB query by ID?Sails.js Waterline 原生 MongoDB 按 ID 查询?
【发布时间】:2016-08-24 05:00:11
【问题描述】:

我正在尝试使用 Waterline .native() 方法在数据库中按 id 查询项目。这是我的代码的样子:

    // Consutruct the query based on type
    var query = {};

    if (req.param('type') === 'id') {
        query = { _id: req.param('number') };
    } else {
        query = { 'data.confirmationNumber': req.param('number') };
    }

    Confirmations.native(function(error, collection) {
        if (error) {
            ResponseService.send(res, 'error', 500, 'Database error.');
        } else {
            collection.find(query).toArray(function(queryError, queryRecord) {
                if (queryError) {
                    ResponseService.send(res, 'error', 500, 'Database error.');
                } else {
                    if (queryRecord.length > 0) {
                        ResponseService.send(res, 'success', 200, queryRecord[0]);
                    } else {
                        ResponseService.send(res, 'error', 404, 'Your confirmation details could not be found.');
                    }
                }
            });
        }
    });

当查询是“data.confirmationNumber”时,它可以工作,但如果它是“_id”,它就不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: mongodb sails.js waterline


    【解决方案1】:

    如果您的 Id 是 ObjectId,请参阅 this

    var ObjectId = require('mongodb').ObjectID; 
    
    {_id: new ObjectId(req.param('number') )}
    

    【讨论】:

      【解决方案2】:

      Iniside Model 和 in 属性这样定义 id 字段

      id : {type : 'objectid',primaryKey:true}

      查询代码时

      这里我的模型名称是 - QuizModel,id 来自参数 quizId,所以这里 quizId 等于 mongodb 数据库中的 _id

      QuizModel.find({_id: QuizModel.mongo.objectId(quizId)})
              .then(function(response){
      
              })
              .catch(function(error){
      
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-01
        • 1970-01-01
        • 2013-12-21
        • 1970-01-01
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多