简体   繁体   中英

Not able to save data in mongoDB using mongoose

I am new to mongoose and mongoDB and I am unable to save data into the collection. Have tried finding solution but nothing seems wrong to me, could anyone please look into this what's getting wrong

This is the model I have defined

const mongoose = require('mongoose')

const { Schema } = mongoose

const ProductSchema = new Schema({
    name: String,
    image: String,
    price: String,
    description: String
})

module.exports = mongoose.model('Product', ProductSchema)

In app.js file

const Product = require('./models/product')

mongoose.Promise = global.Promise;
mongoose.connect(
    'mongodb://127.0.0.1:27017/ecommerce-app',
    { useNewUrlParser: true }
)

app.get('/seeddb', (req, res)=>{
    const data = [
        {
            id: 1,
            name: 'Product name',
            description:'This product details will be shown here',
            image: 'http://placehold.it/355x255',
            price: 12,
            __v: 0
          },
          {
            id: 2,
            name: 'Product name',
            description:'This product details will be shown here',
            image: 'http://placehold.it/355x255',
            price: 24,
            __v: 0
          }]

data.forEach((product)=>{
        const newProduct = new Product({
            name: product.name,
            description: product.description,
            image: product.image,
            price: product.price
        })
        newProduct.save((result)=>{
            if(result){
                console.log('Data is saved into the database')
            }else{
                console.log('Not saved')
            }
        }) // saving products into the database
    })
})

The save promise of mongoose returns error in the first parameter of callback & result in second

So, your data is actually getting saved in DB, but you are evaluating the response wrong

Change the below line in your code

newProduct.save((result)=>{
            if(result){
                console.log('Data is saved into the database')
            }else{
                console.log('Not saved')
            }
        }) // saving products into the database

To,

newProduct.save((error,result)=>{
            if(result){
                console.log('Data is saved into the database')
            }else{
                console.log('Not saved',error)
            }
        }) // saving products into the database

This should work for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM