在声明mongoose文档时,如果多次使用相同的模式,会导致数据重复。为避免这种情况,可以使用mongoose.modelNames()方法检查模型是否已经存在,如果存在,则无需重新声明。
示例代码:
// 引入mongoose模块 const mongoose = require('mongoose');
// 定义模式 const schema = new mongoose.Schema({ name: String, age: Number });
// 检查模型是否已经存在 if (mongoose.modelNames().includes('Person')) { module.exports = mongoose.model('Person'); } else { module.exports = mongoose.model('Person', schema); }