9

I have the following schema set up:

var TradeSchema = new mongoose.Schema({
        channel: String,
        trade: {
            tradeid: Number,
            timestamp: Date,
            datetime: Date,
            marketid: Number,
            marketname: String,
            quantity: Number,
            price: Number,
            total: Number,
            type: String
        }
    });

var MarketSchema = new mongoose.Schema({
        name: { type: String, index: true },
        trades: [TradeSchema]
    });

The Trade schema doesn't actually need to have the "trade" property nested like that, but I am getting it from anAPI and for now I want to keep that exactly as I got it.

The problem is, when I take the raw JS object:

{
    channel: 'trade.5',
    trade: {
        tradeid: '86554823',
        timestamp: 1425569593,
        datetime: '2015-03-05 10:33:13 EDT',
        marketid: '5',
        marketname: 'FTC/BTC',
        quantity: '957.65001732',
        price: '0.00001210',
        total: '0.01158757',
        type: 'Sell'
    }
}

...and I save it...

market.trades.push(trade);
market.save(function(err){
    if (err) console.log('Error saving trade to market.');
});

...it seems to strip out the 'trade' key, and this is all that gets saved to the db:

{ channel: 'trade.5', _id: 54f9e3056e23df1ee3e60327 }

Am I missing a validation step, mass-assignment problem, etc?

EDIT: If I set the TradeSchema to just have an Object type, it saves fine:

var TradeSchema = new mongoose.Schema({
        channel: String,
        trade: Object
    });

Not sure what I would lose since I am new to the Mongo/Mongoose, but it seems like there's probably a downside.

1 Answer 1

19

After creating your Trade object and before pushing it to market.trades, use the markModified function, passing the trade path to it, like this:

trade.markModified('trade');

This will tell Mongoose that this path was modified and save it to the DB. This is required for Mixed schema types.

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

1 Comment

You can also use it like this way, if you already have model with some changed and nested object: market.trades.push(trade); market.markModified('trades'); market.save(); It has worked for me like a charm! Ty.

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.