[英]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.我是 mongoose 和 mongoDB 的新手,我无法将数据保存到集合中。 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在 app.js 文件中
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 mongoose 的保存承诺在回调的第一个参数中返回错误 & 结果在第二个
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这应该适合你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.