如何在架构数组中创建/访问猫鼬架构?

时间:2018-11-13 00:20:52

标签: javascript node.js mongodb mongoose schema

我无法入睡,需要您的帮助,我想为用户创建一个停车历史记录,因此我想到了架构数组中的架构。

现在的问题是:如何在用户中创建新的historySchema对象?以及如何访问,我想在用User.findOne({plate:req.body.plate})获得用户后用数据填充数据吗?

const user = new User({ history: { ... } ? })

`const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const historySchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    date: { type: Date},
    parking_time: { type: Number},
    price: { type: Number},
    parking_id: { type: String},
    carpark_id: { type: String},
    carpark_name: { type: String},
    payment_method: { type: String},
    plate: { type: String}
});

const userSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: { type: String, required: true},
    password: { type: String, required: true},
    name: { type: String, required: true},
    surname: { type: String},
    payment: { type: String},
    plate: { type: Array},
    location : { type: Array},
    history: [historySchema]
    }
);

module.exports = mongoose.model('User', userSchema);`



Parking.findOne({plate: req.body.plate})
.exec()
.then(parking => {
    console.log(parking);
    if (parking !== null){
        User.find({plate: req.body.plate})
        .exec()
        .then(user => { 
            ////HERE IS MY PROBLEM////
            user.history: {
                id: mongoose.Schema.Types.ObjectId,
                date: parking.date 
                plate: parking.plate
                ...
            }
        })

0 个答案:

没有答案