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.
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.
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.
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.
You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With