MongoDB数据填充时title字段显示undefined,求技术排查解决
问题:Mongoose填充数据时title字段显示'undefined undefined'
我用Mongoose定义了ResortSchema,编写seedDB函数填充MongoDB数据,但在mongosh中查询到文档的title字段显示'undefined undefined'。我认为Schema定义正确,怀疑问题出在数组相关逻辑上,已卡多日,请求帮助。相关代码如下:
ResortSchema定义
const mongoose = require ('mongoose'); const Schema = mongoose.Schema; const ResortSchema = new Schema ({ title: String, price: Number, descriptor: String, places: String, location: String }); var Resortdata = mongoose.model('holidayresorts', ResortSchema); module.exports = Resortdata;
index.js 填充逻辑
const sample = array => array[Math.floor(Math.random() * array.lenght)]; const seedDB = async () => { await holidayresorts.deleteMany({}); for (i = 0; i < 5; i++){ const random5 = Math.floor(Math.random() * 5); const Resort = new holidayresorts ({ location: `${cities[random5].city} , ${cities[random5].state}`, title: `${sample(descriptor)} ${sample(places)}` }) await Resort.save(); } } seedDB();
mongosh查询结果
{ _id: ObjectId("630cecf45a6457bfe74c0b9d"), title: 'undefined undefined', location: 'Owerri , Imo', __v: 0 }
问题原因与修复方案
- 数组长度拼写错误:
sample函数中array.lenght是拼写错误,正确应为array.length,错误拼写会导致随机索引计算失效,返回undefined。 - 数组变量未定义:代码中未看到
descriptor和places数组的定义或引入,直接调用sample(descriptor)和sample(places)必然返回undefined。 - 循环变量未声明:
for循环中的i未用let/const声明,会成为全局变量,可能引发意外问题。
修复后的填充逻辑示例:
// 先定义或引入descriptor和places数组 const descriptor = ["奢华", "静谧", "活力", "自然", "复古"]; const places = ["海滩度假村", "山林木屋", "城市酒店", "温泉庄园", "乡村民宿"]; // 确保引入模型和cities数组 const holidayresorts = require('./resortSchema'); // 替换为你的Schema文件路径 const cities = [/* 你的城市数据数组 */]; // 修正sample函数的拼写错误 const sample = array => array[Math.floor(Math.random() * array.length)]; const seedDB = async () => { await holidayresorts.deleteMany({}); // 用let声明循环变量i for (let i = 0; i < 5; i++){ const random5 = Math.floor(Math.random() * 5); const Resort = new holidayresorts ({ location: `${cities[random5].city} , ${cities[random5].state}`, title: `${sample(descriptor)} ${sample(places)}` }) await Resort.save(); } } seedDB();
额外注意:需确保holidayresorts模型和cities数组已正确引入,否则location字段也可能出现异常。
内容的提问来源于stack exchange,提问作者jerryson chibueze
相关产品推荐
相关产品推荐

