如何在模式猫鼬中设置默认值?

时间:2020-10-10 22:26:55

标签: node.js express mongoose

我这里有猫鼬模式

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
        items: {
            type: [{
                id_item: String,
                cnt: Number
            }],
            default: [],
            required: true
        },
        dateExpires: Date
})

cartSchema.pre('save', async function(next) {
    this.dateExpires = Date.now() +  7 * 24 * 60 * 60 * 1000;
})

const modelCart = mongoose.model('Cart', cartSchema);
module.exports = modelCart;

我在以下一条创建模型的路由中调用此函数,如果我发送空值,则它应该在数据库中返回空数组和日期,但返回的是undefined,默认值是不触发。我是Node.js的新手,这可能是个问题吗?

exports.createCart = catchAsync(async (req, res, next) => {
   let newCart = await cartModel.create();
   console.log(newCart); //undefined, wanted items: [], date: ...
        res.status(200).json({
            status: "success",
            data: {
                cart: newCart
            }
        })
    })

1 个答案:

答案 0 :(得分:1)

确定要完全定义该架构吗? Type is a special property in Mongoose schemas.

我认为它应该看起来像这样。

const cartSchema = new mongoose.Schema({
        items: {
            type: Array,
            nested: {
              id_item: { type: String },
              cnt: { type: Number }
            }
            default: [],
            required: true
        },
        dateExpires: Date
})