A
A
Ayan Bai2016-03-19 22:49:20
JavaScript
Ayan Bai, 2016-03-19 22:49:20

How to get an object instead of _id?

I encountered another problem in the project.
I save the order in the database.
controller/create.js

var order = new Order(req.body);
            order.status = mongoose.Types.ObjectId(order.status);
            order.client = order.client ? mongoose.Types.ObjectId(order.client) : null;

After that, I make a virtual field in the model where I access the properties of the client
models/order.js object
OrderSchema.virtual('total').get(function() {
  var order = this,
    result = 0;

  console.log('client, order.client);// Выдает ошибку

  var sumPerHour = order.client.order.sumPerHour % 60; // часы превращаем в минуты
/*
тут делаю операции связанные расчетами итоговой суммы
...
*/
  return result;
});

It starts normally, but when creating an order, it gives an error and in the console instead of an object I get the _id of the client object.
CQtB5U4.png
How to address in this case the client properties from the order model?
In the order model schema, the client property is written as follows:
client: {
    type: Schema.ObjectId,
    ref: 'Client'
  },

*********
And when I request orders, I make a population, everything is fine, there are no problems with this:
var populations = [{
        path: 'driver',
        select: 'name id car',
        populate: {
            path: 'car',
            select: 'model name number',
            model: 'Car' // модель с нижним регистром не находит
        }
    }, {
        path: 'passengers',
        populate: {
            path: 'contact',
            select: 'name phone'
        }
    }];
...
all: function(req, res) {
            Order.find({}).sort('created')
                .populate(populations)
                .populate('user', 'name username')
                .populate('client', 'name title places')
                .populate('direction.from', 'address sum')
                .populate('direction.to', 'address sum')
                .populate('status', 'name key code')
                .exec(function(err, orders) {
                    if (err) {
                        console.log('Cannot list the orders ' + err);
                        return res.status(500).json({
                            error: 'Cannot list the orders'
                        });
                    }
                    res.json(orders);
                });
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Markus Kelvin, 2016-03-23
@wolf47

var order = new Order(req.body);
            order.status = mongoose.Types.ObjectId(order.status);

           /* здесь вы сами же перезаписываете ваш объект в ID*/
          /* order.client = order.client ? mongoose.Types.ObjectId(order.client) : null; */
        order.client = order.client ? order.client : null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question