Reputation: 97
My mongoose schema:
const BillSchema = new Schema({
fromDate: { type: Date, default: Date.now },
toDate: { type: Date, default: Date.now },
phoneNumber: { type: String },
created: { type: Date},
user: { type: Schema.ObjectId, ref: 'User' },
billDetail: [{ type: Schema.Types.ObjectId, ref: 'BillDetail' }]
});
const BilldetailSchema = new Schema({
amount: { type: Number },
item: { type: Schema.ObjectId, ref: 'Item' },
created: { type: Date, default: Date.now },
user: { type: Schema.ObjectId, ref: 'User' }
});
const ItemSchema = new Schema({
name: { type: String},
code: { type: String},
amount: { type: Number },
created: { type: Date, default: Date.now },
user: { type: Schema.ObjectId, ref: 'User' }
});
My Json get from client
{ billDetail: [ { item: [Object], amount: 1, rentalPrice: 11, rentalDays: 1 } ],
code: '000001',
customerName: 'steve',
phoneNumber: '959494949',
fromDate: '2017-05-07T17:00:00.000Z',
toDate: '2017-05-18T17:00:00.000Z' }
How can i parse json string above to bill object? I try to use this code:
let bill = new Bill(req.body);
but it's not working, it's only returning bill, but not billdetails.
Upvotes: 1
Views: 1535
Reputation: 366
billDetail
should be an array of ids, not the objects.
You can insert bill details first, obtain their ids, and then push them to a new billDetail
array.
BillDetail.insertMany(req.body.billDetail)
.then(function(billDetails) {
const billDetail = billDetails.map(billDetail => billDetail._id);
const billData = Object.assign({}, req.body, { billDetail });
const bill = new Bill(billData);
})
.catch(function(err) {
// error handling here
});
Upvotes: 1