简体   繁体   中英

Mongodb one to many associations embedded cannot read property push of undefined

I'm starting with associations in Mongodb and I'm running into that error when I try to push the post contents to one user using the embedded process:

Cannot read property 'push' of undefined

This is my code:

 var mongoose= require("mongoose"); mongoose.connect("mongodb://localhost/associations"); // User var userSchema = new mongoose.Schema({ name: String, email: String }); var User= mongoose.model("User", userSchema); // POst var postSchema = new mongoose.Schema({ title: String, content: String }); var Post= mongoose.model("Post", postSchema); var newUser= new User({ name: "Roy", email: "c@gmail.com", posts: [postSchema] }); newUser.posts.push({ title: "Myself", content: "I'm happy" }); newUser.save(function(err,user){ if (err) { console.log(err); }else{ console.log(user); } }); 

It was an issue about the order, the Post Schema and model should go before the user Schema and model. This is the proper way to store things:

 var mongoose= require("mongoose"); mongoose.connect("mongodb://localhost/associations"); // POst var postSchema = new mongoose.Schema({ title: String, content: String }); var Post= mongoose.model("Post", postSchema); // User var userSchema = new mongoose.Schema({ name: String, email: String, posts: [postSchema] }); var User= mongoose.model("User", userSchema); var newUser= new User({ name: "Roy", email: "c@gmail.com" }); newUser.posts.push({ title: "Myself", content: "I'm happy" }); newUser.save(function(err,user){ if (err) { console.log(err); }else{ console.log(user); } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM