如何保存多个for循环数据?

时间:2019-03-09 07:40:30

标签: mongodb api express mongoose-schema

在发布请求中,我要提取objectId的数据并将其保存在数据库中。将有2或3个objectId,我将在数组中获取它。从该数组中,我可以使用单独的“ for循环”提取数据,但是最后,我无法保存数据。 我想知道如何将数据从一个数组移动到另一个数组或直接保存数据。

模式:-

const jobSch = new Schema({
    token : {type:Number},
    name : {type:String},
    phoneNumber: {type:Number},
    gender : {type:String},
    stage : {type:String},
    categoryId : [Schema.Types.ObjectId],
    subCategoryId : [Schema.Types.ObjectId],
    serviceId : [Schema.Types.ObjectId],
    category : [String],
    subcategory : [String],
    service: [String],
    paymenttype: [String],
    tax: {type:Number},
    totalprice: {type:String},
    servicePerson: {type:String},
    createdOn : {type:Date, default:new Date()},
    updatedOn : {type:Date, default:new Date()}   
});

POST请求代码:-

router.post('/', async (req, res) => {
    let ids = req.body;
    let catId = ids.categoryId;
    console.log("catId", catId)
    console.log("catId.length", catId.length)
    let subcatId = ids.subCategoryId;
    console.log("subcatId", subcatId);
    console.log("subcatId.length", subcatId.length)
    let serId = ids.serviceId;
    console.log("serId", serId);
    console.log("subcatId.length", serId.length)
    let job = new Job(ids);
    let catgy=[];
    let subcatgy=[];
    let subser=[];

    for (i = 0; i < catId.length; i++) {
        Category.findById(catId[i])
            .then(category => {
                if (category && category != null) {
                    console.log('category.name', category.name);
                    catgy.push(`${category.name}`)
                    console.log(catgy);

                }
            })
    }
    for (i = 0; i < subcatId.length; i++) {
        Service.findById(subcatId[i])
            .then(service => {
                if (service && service != null) {
                    console.log('service.name', service.name);
                    subcatgy.push(`${service.name}`)
                    console.log(subcatgy);

                }
            })
    }
    for (i = 0; i < serId.length; i++) {
        Subservice.findById(serId[i])
            .then(subService => {
                if (subService && subService != null) {
                    console.log('subservice.name', subService.subService);
                    subser.push(`${subService.subService}`)
                  console.log(subser);
                }
            })
    }
    var category = catgy.slice();
    console.log("category1", category)
    var service = subcatgy.slice();
    console.log('service2', service);
    var subService = subser.slice();
    console.log('subService3',subService);
    console.log(job);
    job.save().then(job => {
        res.status(201).json({
            message: 'Job saved successfully', job
        })
    }).catch(err => console.log(err));
});

1 个答案:

答案 0 :(得分:1)

问题在于,已解析的承诺(findById)的回调函数是异步执行的。尝试检查this,我认为它将为您提供帮助。