i need some help please, i try to seed some data to mongoDB Atlas, so i code (thanks Basir^^) a api for this :
productRouter.get('/seed', expressAsyncHandler(async (req, res) => {
console.log('foo');
/* await Product.remove({})*/
const seller = await User.findOne({
isSeller: true
})
if (seller) {
const products = data.products.map((product) => ({
...product,
seller: seller._id,
}));
const createdProducts = await Product.insertMany(data.products);
res.send({
createdProducts
});
} else {
res.status(500).send({
message: 'No seller found. first run /api/users/seed'
});
}}));
the problem, when i enter my api route in the browser he return this :
"Cast to ObjectId failed for value "seed" at path
"_id" for model "Product""
The other routes works perfectly, i’m really confused…
This is the productSchema:
import mongoose from 'mongoose'
import {
reviewSchema
} from './reviewSchema.js'
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
image: {
type: String,
required: true,
},
brand: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
rating: {
type: Number,
required: true,
},
numReviews: {
type: Number,
required: true,
},
reviews: [reviewSchema]
}, {
timestamps: true
})
export const Product = mongoose.model("Product",
productSchema)
this my server.js :
import {config} from 'dotenv'
import express from 'express'
import mongoose from 'mongoose'
import path from 'path'
import{productRouter}
from'./routers/productRouter.js';
import {userRouter} from './routers/userRouter.js'
import {orderRouter} from './routers/orderRouter.js'
import {uploadRouter} from
'./routers/uploadRouter.js';
const dotenv = config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
mongoose.connect(process.env.MONGODB_URL ||
'mongodb://localhost/ecommercelab', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
app.use('/api/uploads', uploadRouter);
app.use('/api/users', userRouter);
app.use('/api/products', productRouter);
app.use('/api/orders', orderRouter);
app.get('/api/config/paypal', (req, res) => {
res.send(process.env.PAYPAL_CLIENT_ID || '');
});
app.get('/api/config/google', (req, res) => {
res.send(process.env.GOOGLE_API_KEY || '');
});
const __dirname = path.resolve()
app.use('/uploads',
express.static(path.join(__dirname, 'uploads')));
app.use(express.static(path.join(__dirname,
'/frontend/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname,
'/frontend/build/index.html'));
});
app.use((err, req, res, next) => {
res.status(500).send({
message: err.message
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serve at http://localhost:${port}`);
});
Its for a Ecommerce app.
Thanks for your attention, i continue to test on my side 😉
2
Answers
Ok, after three hour to try it i finally solved this issue, i discovered the light ^^. Its just, my route(/seed) was positioned just behind a route with/:id, it seems that it created a kind of conflict, i moved her higher in the file productRouter its ok now. : )
My guess is that you should replace
const createdProducts = await Product.insertMany(data.products);
withconst createdProducts = await Product.insertMany(products);
. You are referencigndata.products
but a few lines before you were working withconst products = data.products.map( ...
EDIT: This will only solve your incoming issue that the
seller
id in your DB is missing for the product entries 😀