S
S
semki0962020-09-01 15:04:12
JavaScript
semki096, 2020-09-01 15:04:12

What does 'export default mongoose.models' mean?

Source https://github.com/vercel/next.js/blob/canary/exam...
There is such a model in models/Pet.js.

import mongoose from 'mongoose'
const PetSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please provide a name for this pet.'],
    maxlength: [20, 'Name cannot be more than 60 characters'],
  },
  ......
})
export default mongoose.models.Pet || mongoose.model('Pet', PetSchema)

Export mongoose.model('Pet', PetSchema)is probably we are exporting our model, but what does mongoose.models.Pet? I would be grateful for help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-09-01
@semki096

https://learn.javascript.ru/logical-ops#ili

S
semki096, 2020-09-01
@semki096

Understood. Here is the solution

/* проверяем, существует ли модель, затем используйте ее (mongoose.models.Product), иначе создаем ее (mongoose.model('Product', ProductSchema) 
*  При первом вызове функции создания модели mongoose сохраняет модель под указанным вами ключом (например, «пользователи»). Если вы вызовете функцию создания модели с одним и тем же ключом более одного раза, мангуст не позволит вам перезаписать существующую модель.
*/
export default mongoose.models.Product || mongoose.model('Product', ProductSchema)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question