1

Cant figure something out.

my API is sending out the whole object under an array for one of my routes despite it being identical in schema to another route that is returning the object just fine.

The only difference is one uses FindById but the other uses an extra $eq to search for a specific field in the objects to match with.

The FindById returns my objects normal but the one thats using $eq is returning it inside an array. Their schemas are identical. Is this just an idiosyncrasy I have to deal with?

    apiRouter.get('/accts/:acct_id', function(req, res) {
    Acct.find( ({ acct_id: { $eq: req.params.acct_id } } ), function(err, acct) {
            if (err) res.send(err);

        res.json(acct);
    });
});


apiRouter.route('/users/:user_id')

    // get the user with that id
    .get(function(req, res) {
        User.findById(req.params.user_id, function(err, user) {
            if (err) res.send(err);

            // return that user
            res.json(user);
        });
    })

And the controller thats binding the data.

.controller('acctView', function($routeParams, Acct) {

    var vm = this;

    // set a processing variable to show loading things
    vm.processing = true;

    Acct.get($routeParams.accts_id)
        .success(function(data) {

            vm.processing = false;

            vm.accts = data;

        });

});

I end up having to use acct.accts[0].acct_id to access my object in angular whereas all my other pages do not receive the object as an extra array.

schema if needed:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

    // acct schema 
    var AcctSchema   = new Schema({
        acct_id: String,
        acct_name: String,
        acct_address_1: String,
        acct_address_2: String,
        acct_address_city: String,
        acct_address_state: String,
        acct_address_zip: Number,
        acct_address_country:  String,
        recipients: [],
        notes: {
            dist: String,
            misc: String
        }   
    });

module.exports = mongoose.model('Acct', AcctSchema);

1 Answer 1

4

findById() return only one document. While find() return multiple document in an array. You could use findOne() instead of find(), it will return only one document.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh that makes sense. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.