Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Can't save nested object to nested model

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.

like image 293
crypticsymbols Avatar asked Mar 06 '15 17:03

crypticsymbols


People also ask

What does save () return in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What does .save do Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

Can we overwrite Mongoose default ID with own id?

You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.

Can we create Mongoose model without schema?

You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.


1 Answers

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.

like image 132
victorkt Avatar answered Oct 02 '22 14:10

victorkt