This is the order model
const mongoose=require('mongoose');
const items = require('../models/item_model');
const orderSchema=mongoose.Schema({
item_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Item',
require: true
},
handicraftmen_id : {type: String ,require: true},
customer_id : {type: String ,require: true},
quantity : {type : Number,default: 1},
status : {type : Number,default:1},
amount:{type:Number,require:true},
createDate :{type: String, require:true},
},{timestamps: true});
module.exports = mongoose.model('Order',orderSchema);
and my request body is kind of like an array below.
[
{
"item_id": "62fa132d8c29dac0417afd36",
"handicraftmen_id":"62fa132d8c29dac0417afd89",
"cutomer_id":"62fa132d8c29dac0417agf45",
"qty": "4",
"amount":"2000"
},
{
"item_id": "62fa132d8c29dac0417afd36",
"handicraftmen_id":"62fa132d8c29dac0417afd89",
"cutomer_id":"62fa132d8c29dac0417agf45",
"qty": "1",
"amount":"500"
},
{
"item_id": "62fa132d8c29dac0417afd36",
"handicraftmen_id":"62fa132d8c29dac0417afd89",
"cutomer_id":"62fa132d8c29dac0417agf45",
"qty": "3",
"amount":"1500"
}
]
I want to add the above request body one by one into the database.
how should I add this using node and mongoose queries?
CodePudding user response:
have a look at the code below does something similar. refer to the link https://www.tutorialkart.com/nodejs/mongoose/insert-multiple-documents-to-mongodb/
// make a connection
mongoose.connect('mongodb://localhost:27017/tutorialkart');
// get reference to database
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
// define Schema
var BookSchema = mongoose.Schema({
name: String,
price: Number,
quantity: Number
});
// compile schema to model
var Book = mongoose.model('Book', BookSchema, 'bookstore');
// documents array
var books = [{ name: 'Mongoose Tutorial', price: 10, quantity: 25 },
{ name: 'NodeJS tutorial', price: 15, quantity: 5 },
{ name: 'MongoDB Tutorial', price: 20, quantity: 2 }];
// save multiple documents to the collection referenced by Book Model
Book.collection.insert(books, function (err, docs) {
if (err){
return console.error(err);
} else {
console.log("Multiple documents inserted to Collection");
}
});
});
[1]: https://www.tutorialkart.com/nodejs/mongoose/insert-multiple-documents-to-mongodb/