JackH
JackH

Reputation: 4745

Sails.js Waterline native MongoDB query by ID?

I am trying to use the Waterline .native() method to query an item by id in the database. This is what my code looks like:

    // 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.');
                    }
                }
            });
        }
    });

When the query is 'data.confirmationNumber' it works but if it is '_id' it dows not work. How do I fix this?

Upvotes: 0

Views: 1303

Answers (2)

selftaught91
selftaught91

Reputation: 7481

Iniside Model and in attribute define the id field like this

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

When you are querying the code

Here my model name is - QuizModel and the id is coming in the params quizId so here quizId is equal to the _id in the mongodb database

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

        })
        .catch(function(error){

        });

Upvotes: 2

jhonny lopez
jhonny lopez

Reputation: 325

if your Id is a ObjectId see this

var ObjectId = require('mongodb').ObjectID; 

{_id: new ObjectId(req.param('number') )}

Upvotes: 2

Related Questions