这是我的代码
模型.ts
import mongoose from 'mongoose';
interface CustomerAttributes {
shopId: string;
firstName: string;
lastName: string;
...... }
interface CustomerModel extends mongoose.Model<CustomerDoc> {
build(attributes: CustomerAttributes): CustomerDoc;
}
interface CustomerDoc extends mongoose.Document {
.....
}
const CustomerSchema = new mongoose.Schema({
.........
});
CustomerSchema.statics.build = (attributes: CustomerAttributes) => {
return new Customer(attributes);
};
const Customer = mongoose.model<CustomerDoc, CustomerModel>('Customer', CustomerSchema);
export { Customer };
索引.ts
import {app} from './app';
const start = async ()=>{
try {
await mongoose.connect('mongodb+srv://*****:****@cluster0.hpphw.mongodb.net/test')
console.log('Connected to MongoDB');
}catch(err){
console.log(err);
}
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
}
start();
并且 app.js 文件调用每个路由。
app.use("/api/v1/business/customer", customerRouter);
app.all("*", async (req, res) => {
throw new NotFoundError();
});
app.use(errorHandler);
export { app };
我正在尝试从 mongodb 获取数据并使用 fast-csv 将数据写入 csv 文件。这是我为将数据获取为 csv 文件而编写的代码。
和 route.ts
// get all customer data as csv
router.get('/export',
currentUser,
async (req: Request, res: Response) => {
const customers = await Customer.find({});
var ws = fs.createWriteStream("./data/data.csv");
fastcsv
.write(customers, { headers: true })
.on("finish", () => {
res.send("exported");
})
.pipe(ws)
});
export { router as customerRouter };
在数据目录中,它创建 data.csv 文件。但是从数据库中读取的数据没有写入。我该如何解决这个问题