Mongodb嵌入的一对多关联无法读取未定义的属性推送

时间:2017-01-13 17:24:17

标签: node.js mongodb mongoose

我从Mongodb中的关联开始,当我尝试使用嵌入式进程将帖子内容推送给一个用户时,我遇到了这个错误:

无法读取未定义的属性'push'

这是我的代码:

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);
	}
});

1 个答案:

答案 0 :(得分:0)

这是关于订单的问题,Post Schema和模型应该在用户Schema和model之前。这是存储事物的正确方法:

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);
	}
});