TypeError:无法读取属性' push'未定义的 - expressjs mongodb

时间:2018-04-21 08:30:17

标签: node.js mongodb express mongoose

我正在尝试使用mongoose和expressjs在MongoDB中学习一对多的关系。我正在尝试使用只存储id作为参考的引用方法。

用户已创建。这是我的代码 -

var mongoose = require("mongoose");

//saving application name in mongodb and connecting to it
mongoose.connect("mongodb://localhost/blog_demo_3");

//POST - title, content
var postSchema = mongoose.Schema({
    title: String,
    content: String
});


var Post = mongoose.model("Post", postSchema);

//USER - name email
var userSchema = mongoose.Schema({
    email: String,
    name: String,
   //linking to many posts specific to user one to many relation    
posts: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post"
    }
]
});

var User = mongoose.model("User", userSchema);

Post.create({
    title: "How to cook burger pt 2",
    content: "blah blah blah"
}, function(err, post){
    User.find({name: "Bob Fischer"}, function(err, foundUser){
        if(err)
            console.log(err);
        else {
            //foundUser.posts.pus(post) - doesn't works
            foundUser.posts.push(post._id);
            foundUser.save(function(err, data){
                if(err)
                    console.log(err)
                else
                    console.log(data);
            });
        }
    });
});

 // User.create({
 //     email: "bob@foodtech.com",
 //     name: "Bob Fischer"
 // }, function(err, createdBlog){
 //     if(err)
 //         console.log(err);
 //     else
 //         console.log(createdBlog);
 // });

请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

我很抱歉没有注意到这么小的语法错误。

User.find({name: "Bob Fischer"}, function(err, foundUser){

应该是

User.findOne({name: "Bob Fischer"}, function(err, foundUser){