TypeError:user.save不是函数[mongoose]

时间:2019-06-18 20:53:23

标签: javascript mongodb mongoose

这是我的代码,无法处理此问题。试图摆脱此功能,但无济于事。 代码=>

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/blog_demo_2", {useNewUrlParser: true});

//post - content, title

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

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

//user - email, name
var userSchema = new mongoose.Schema({
    email: String,
    name: String,
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Post"
        }
    ]
});

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

这是问题函数,不了解是什么导致错误。我以为这是postModel的问题,但是不:

postModel.create({
    title: "How to be fat like Andjelka Kozakivnayadura",
    content: "Eat burgers, pizzas, and Coke Cole bittcheeies"
}, function(err, post){
    if (err){
        console.log(err);
    } else {
        User.find({email: "gangbit@protonmail.com"}, function(err, user){
           if (err){
               console.log(err);
           } else {
               user.posts = user.posts || [];
               user.posts.push(post);
               user.save(function(err, data){
                   if (err){
                       console.log(err);
                   } else {
                       console.log(data);
                   }
               });
           }
        });
    }
});

2 个答案:

答案 0 :(得分:0)

尝试使用Spread Operator {...someObj}克隆对象。

User.find({email: "gangbit@protonmail.com"}, function(err, user){
       if (err){
           console.log(err);
       } else {
           const userObj = {...user };

现在,您可以尝试将push数据导入posts。您也可以使用功能convert mongodB document to JS object toObject()

User.find({email: "gangbit@protonmail.com"}, function(err, user){
       if (err){
           console.log(err);
       } else {
           const userObj = user.toObject();

答案 1 :(得分:0)

User.find({email: "gangbit@protonmail.com"}, function(err, user){

这将返回一个用户数组,而不是单个用户。

您要使用findOne

下次console.log(user)