i’m making a todolist (angela yu), i’m trying to write to a new database, but i keep getting error.this is the error:
C:UserstunjiDesktopwebdevtodolist-v2-starting-filesnode_modulesmongooselibmodel.js:3519
for (let i = 0; i < error.writeErrors.length; ++i) {
^
TypeError: Cannot read properties of undefined (reading 'length')
at C:UserstunjiDesktopwebdevtodolist-v2-starting-filesnode_modulesmongooselibmodel.js:3519:47
at collectionOperationCallback (C:UserstunjiDesktopwebdevtodolist-v2-starting-filesnode_modulesmongooselibdriversnode-mongodb-nativecollection.js:133:26)
at Timeout.<anonymous> (C:UserstunjiDesktopwebdevtodolist-v2-starting-filesnode_modulesmongooselibdriversnode-mongodb-nativecollection.js:160:11)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
this is the code:
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");
});
i’ve checked the server, deleted and installed the node module ,everything, still no fix,nothing at all
3
Answers
I think you cannot connect to mongoose, as per mongoose documentation connect is an async method.
Try waiting for connection to be established, then write to the database
example:
Instead of using localhost:27017
Rather use 127.0.0.1:27017
So it should look like this:
To solve this problem you have first to comment the tiem.insert and your array
after that run the app.js in the terminal, now move to the mongo or mongosh and write show dbs, you should now see the todolistDB already. so now you could go and uncomment the rest of your code and run thr app.js again