开发者问题收集

TypeError:使用 mongoose 时无法读取未定义的属性(读取‘length’)

2023-01-07
1625

我正在制作一个待办事项列表(angela yu),我试图写入一个新的数据库,但我一直收到错误。这是错误:

C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\model.js:3519
        for (let i = 0; i < error.writeErrors.length; ++i) {
                                              ^

TypeError: Cannot read properties of undefined (reading 'length')
    at C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\model.js:3519:47
    at collectionOperationCallback (C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:133:26)
    at Timeout.<anonymous> (C:\Users\tunji\Desktop\webdev\todolist-v2-starting-files\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:160:11)        
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7)

这是代码:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();
mongoose.connect('mongodb://localhost:27017/todolistDB');

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));


// const itemsSchema = {
//   name: String
// };

const itemsSchema = new mongoose.Schema({
  name: String
});

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({name: "Workout"});
const item2 = new Item({name: "skydive"});
const item3 = new Item({name: "bungee"});

const defaultItems = [item1, item2, item3];

Item.insertMany(defaultItems, function(err){
  if (err){
    console.log(err + "yea");
  } else {
    console.log("good to go");
  }
});

app.get("/", function(req, res) {


  res.render("list", {listTitle: "Today", newListItems: items});

});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

我检查了服务器,删除并安装了节点模块,一切正常,仍然没有修复,什么都没有

3个回答

不要使用 localhost:27017 而要使用 127.0.0.1:27017

因此它应如下所示:

mongoose.connect("mongodb://127.0.0.1:27017/todolistDB")
Jerrell-Abrahams
2023-02-15

我认为您无法连接到 mongoose,因为根据 mongoose 文档,连接是一种异步方法。

尝试等待建立连接,然后写入数据库

示例:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

app.get("/", function(req, res) {
  res.render("list", {listTitle: "Today", newListItems: items});
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

async function connect() {
    try {
        await mongoose.connect('mongodb://localhost:27017/todolistDB');
        console.log('Connected to MongoDB');
    } catch (error) {
        console.log('Could not connect to MongoDB');
        throw error;
    }
    const itemsSchema = new mongoose.Schema({
        name: String
    });
      
    const Item = mongoose.model("Item", itemsSchema);  
    const item1 = new Item({name: "Workout"});
    const item2 = new Item({name: "skydive"});
    const item3 = new Item({name: "bungee"});
    
    const defaultItems = [item1, item2, item3];
    
    Item.insertMany(defaultItems, function(err){
    if (err){
        console.log(err + "yea");
    } else {
        console.log("good to go");
    }
    });
      
}

connect();

``
D.J.
2023-01-07

要解决这个问题,你首先要注释掉 tiem.insert 和你的数组

const itemsSchema = new mongoose.Schema({
  name: String
});

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({name: "Workout"});
const item2 = new Item({name: "skydive"});
const item3 = new Item({name: "bungee"});

// const defaultItems = [item1, item2, item3];

// Item.insertMany(defaultItems, function(err){
//   if (err){
//     console.log(err + "yea");
//   } else {
//     console.log("good to go");
//   }

然后在终端中运行 app.js,现在转到 mongo 或 mongosh 并写入 show dbs ,你现在应该已经看到 todolistDB 了。所以现在你可以取消注释其余代码并再次运行 app.js

Bassem Mahdi
2023-03-29