簡體   English   中英

TypeError:image.save不是函數,同時使用mongoose和express創建新文檔

[英]TypeError: image.save is not a function, while creating a new document with mongoose and express

我正在創建一個新產品,保存后,繼續使用findById搜索它,然后嘗試創建另一個文檔“ Image”,該文檔在Product模式中被引用。 當我執行代碼時,它給我TypeError: image.save is not a function 我該如何解決?

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

您不應該將圖像聲明為Schema ImageSchema的新對象嗎? 在我看來,您沒有創建對象。

在您的函數中,我將執行以下操作:

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

然后,我將調用save函數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM