2017-02-13 10 views
0

私は新しい製品を作成しています。保存した後、私はmongoose findByIdで検索します。製品スキーマ内で参照されている「イメージ」です。コードを実行すると、それは私にTypeError: image.save is not a functionを与えます。私はこれをどのように修正すべきですか?TypeError:image.saveは関数ではありません。mongooseとexpressで新しい文書を作成しています

Product.create(req.body.product, function(err, product) { 
     if (err) { 
      console.log(err); 
     } else { 
      product.save(); 
      Product.findById(product._id, function(err, foundProduct) { 
       if (err) { 
        req.flash('error', err.message); 
        res.redirect('/product'); 
       } else { 
        Image.create(req.files, function(err, image) { 
         if (err) { 
          req.flash('error', err.message); 
          res.redirect('/product'); 
         } else { 
          image.save(); 
          foundProduct.images.push(image); 
          foundProduct.save(); 
          res.redirect('/product/' + product._id); 
         } 
        }); 
       } 
      }); 
     } 
    }); 

これは私のスキーマです:

var productSchema = new mongoose.Schema({ 
    name: String, 
    price: String, 
    description: String, 
    gender: String, 
    images: [{ 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "Image" 
    }], 
    sizes: { 
     ch: Number, 
     m: Number, 
     g: Number, 
     eg: Number 
    }, 
    type: String, 
    likes: Number, default: 0 
}); 


var imageSchema = new mongoose.Schema({ 
    public_id: String, 
    url: String, 
    secure_url: String, 
    resource_type: String, 
    format: String, 
    bytes: String 
}); 

答えて

0

あなたはスキーマImageSchemaの新しいオブジェクトとして、あなたのイメージを宣言するべきではないでしょうか。あなたはそのオブジェクトを作成していないようです。

const im = new Image(); 
im.url = ... 

その後、私は、保存関数の呼び出しになるだろう:私は次のことを行うと、あなたの関数内

im.save().then((data,error) => {...}) 
+0

ありがとうございました。この場合、.createメソッドが動作しなかった理由に関する提案はありますか?私はそれが魅力のように動作するコードの他の部分を持っています。 – tFranzoni

+0

正直言って、私はこの.create関数を使ったことはありません。 .save関数は、常にdbに文書を保存する主な方法でした。しかし、私はそれをオンラインで見て、それはオブジェクトを保存するより汎用的な関数である(これは必ずしもモデルのインスタンスである必要はない)のようだ。 .save中にオブジェクトをインスタンス化する必要があります(私は "new Image()"と同じように)。私はセーブに何の問題もなかったので、あなたがそれを使うだけであれば問題はないと思います。 http://stackoverflow.com/questions/38290684/mongoose-save-vs-insert-vs-create http://mongoosejs.com/docs/api.html –

関連する問題