将json解析为Mongoose模式

时间:2017-05-18 03:10:30

标签: json node.js express mongoose mongoose-schema

我的猫鼬模式:

NAME="Ubuntu"
VERSION="14.04.2 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.2 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

我的Json从客户端

extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        if text == "\n" {
            textView.resignFirstResponder()
            return false
        }
        return true
    }
}

如何将json字符串解析为bill对象?我尝试使用这段代码:

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' }
});

但是它不起作用,它只是返还账单,而不是账单。

1 个答案:

答案 0 :(得分:1)

billDetail应该是一个id数组,而不是对象。

您可以先插入帐单详细信息,获取其ID,然后将其推送到新的billDetail数组。

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
    });