保存之前更新猫鼬模型

时间:2020-02-21 19:33:27

标签: node.js mongodb mongoose async-await

我正在尝试用这段代码在保存之前更新book_id。 因此每次book_id都会保持集合长度(尝试实现MySQL自动递增) 如果有更好的方法请引用它。

我的问题是,为什么在我们将book_id移到next()回调中之前,Book.find的值不会改变

const BookSchema = new Schema({
    book_id: {
        type: Number,
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        require: true
    },
    writer: {
        type: String,
        required: true
    }
});


BookSchema.pre('save', function(next)  {
    Book.find({}, ( err, books) => {
        this.book_id = books.length;
        // next()
    });
    next()    
});
const Book = mongoose.model('book', BookSchema)

0 个答案:

没有答案
相关问题