Why is Mongoose replacing key/value pair in an object with _id?
The issue is that the first object you're trying to save:
console.log(stockObject);// { 'F': '2' }
Doesn't match the Schema
you've defined for it:
{ symbol: String, amount: Number}
Mongoose normalizes objects it saves based on the Schema
, removing excess properties like 'F'
when it's expecting only 'symbol'
and 'amount'
.
if(req.body.verb === 'buy') { stockObject.symbol = stock; stockObject.amount = amount;}
To get the output as [{"F": "2"}]
, you could .map()
the collection before sending it to the client:
res.json({ stocks: user.stocks.map(function (stock) { // in ES6 // return { [stock.symbol]: stock.amount }; var out = {}; out[stock.symbol] = stock.amount; return out; });});
Or, use the Mixed
type, as mentioned in "How do you use Mongoose without defining a schema?," that would allow you to store { 'F': '2' }
.
var UserSchema = new Schema({ id: String, stocks: [{ type: Schema.Types.Mixed }]});