Reputation: 43
Please forgive me if there is already a thread that addresses my problem, but i could not find it.
I'm pretty new to web development, and am currently working on course material from one of udemy's full stack developer classes.
I'm using node with express and mongoDB with mongoose. Currently, the project is to upgrade a pre-existing to-do app we built earlier in the course(big surprise eh?) with mongoDB.
everything is going fine up until a point, where I cannot seem to recreate the instructors results.
The trouble is when I try to use express route parameters to generate new lists (and thus new database collections) dynamically.
const listItemsSchema = new mongoose.Schema({
name: String
});
//create collection
const ListItem = mongoose.model("ListItem", listItemsSchema);
const item1 = new ListItem({
name: "item1"
});
const item2 = new ListItem({
name: "item2"
});
const item3 = new ListItem({
name: "item3"
});
const defaultItems = [item1, item2, item3];
const listSchema = new mongoose.Schema({
name: String,
items: [listItemsSchema]
});
const List = mongoose.model("List", listSchema);
app.get("/:listName", (req, res) => {
const newListName = req.params.listName;
console.log(newListName); //logs new list name correctly
console.log(defaultItems); //logs default items array correctly
const newList = new List({
name: newListName,
list: defaultItems
});
newList.save();
console.log(newList); // logs the name field correctly, however, logs the items array as empty
});
when I look at the collection in the mongo shell, its the same story. the default items array contents are not saved and i cannot for the life of me figure out why.
Upvotes: 0
Views: 55
Reputation: 376
That's because your listSchema
definition has property items
but you are instantiating it with property list
Change your code as follow:
const newList = new List({
name: newListName,
items: defaultItems
});
Also note that newList.save()
is an asynchronous operation and you have to wait for it to be resolved.
newList.save()
.then((result) => {
console.log(result);
}
or in an async function:
const result = await newList.save();
console.log(result);
Upvotes: 1