اذهب إلى المحتوى
  • 0

ضبط زمن انتهاء الصلاحية : node, express, mongoose

Hadi255

السؤال

مرحبا 

أحاول ضبط زمن انتهاء الصلاحية منذ يومين عبثاُ ، تنتهي الصلاحية دوما بعد دقيقتين تقريبا وكأنها قيمة افتراضية لم أستطع تغييرها.

Carsts.js:

const mongoose = require('mongoose');
const cartSchema = mongoose.Schema({
    _id: {
        required: true,
        type: String
    },
    totalquantity: {
        required: true,
        type: Number
    },
    totalPrice: {
        required: true,
        type: Number
    },
    selectedProduct: {
        required: true,
        type: [],// or Array
    },
    createAt: {
        type: Date,
        expires: 10,
        // expires: '10',
        // index: { expireAfterSeconds: 5 }
        // index:{expires:'1m'}
    }
}, { timestamps: true })

module.exports = mongoose.model('Carts', cartSchema);

التعليقات هي فقط بعض المحاولات الكثيرة التي قمت بها .

index.js:

router.get('/addTocart/:id/:price/:name', (req, res, next) => {
  const product_id = req.params.id;
  const cartId = req.user._id;
  const newproductPrice = +req.params.price;
  const newProduct = {
    _id: req.params.id,
    price: newproductPrice,
    name: req.params.name,
    quantity: 1
  };
  Carts.findOne({ _id: cartId })
    .catch((err) => { console.log("Error! :", err) })
    .then((cart) => {
      if (!cart) {
        const newCart = new Carts({
          _id: cartId,
          totalquantity: 1,
          totalPrice: newproductPrice,
          selectedProduct: [newProduct],
          createAt: Date.now(),
        })
        newCart.save({})
          .catch((err) => { console.log(err) })
          .then((result) => {
            console.log('New user: ', result)
          })
      }
      if (cart) {
        var indexOfProduct = -1;
        for (var i = 0; i < cart.selectedProduct.length; i++) {
          if (product_id === cart.selectedProduct[i]._id) {
            indexOfProduct = i;
            break;
          }
        }
        if (indexOfProduct >= 0) {
          // console.log(cart.selectedProduct[indexOfProduct]);
          cart.selectedProduct[indexOfProduct].quantity++;
          cart.selectedProduct[indexOfProduct].price += newproductPrice;
          cart.selectedProduct[indexOfProduct].price =
            Math.round(cart.selectedProduct[indexOfProduct].price * 100) / 100;
          cart.totalquantity++;
          cart.totalPrice += newproductPrice;
          cart.totalPrice = Math.round(cart.totalPrice * 100) / 100;
			cart.createAt = Date.now();
          // cart.createAt = Date.now();
          Carts.updateOne({ _id: cartId }, { $set: cart })
            .catch((err) => { console.log(err) })
            .then((result) => {
              console.log('update:', result);
              console.log('cart-update: ', cart);
            })
        }
        else {
          cart.totalquantity++;
          cart.totalPrice += newproductPrice;
          cart.totalPrice = Math.round(cart.totalPrice * 100) / 100;
          cart.selectedProduct.push(newProduct);

          cart.createAt = Date.now();
          Carts.updateOne({ _id: cartId }, { $set: cart })
            .catch((err) => { console.log(err) })
            .then((result) => {
              console.log('add:', result);
              console.log('cart-add: ', cart);
            })
        }
      }
    })
  next();
  res.redirect('/');
});

إضافة لذلك أنه يوجد تداخل ، أي عندما أبدل إلى مستخدم آخر ( بتسجيل الخروج والدخول باسم آخر ) يتنتهي مدة صلاحية الثاني و يتم حذف كرته رغم أنه يجب أن لا تنتهي بعد.


 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

لا يوجد أي إجابة أو حتى تفاعل، هل السؤال أو الأكواد غير واضحة أو غير مفهومة ؟! 

يمكنني تعديلها أو توضيحها إن إن كان ضرورياً .

تم التعديل في بواسطة Hadi255
رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

مشكلة انتهاء الصلاحية في نموذج Carts.js لديك هي أنك تستخدم قيمة ثابتة لـ expires، والتي هي 10، مما يعني أن العنصر سينتهي صلاحيته بعد 10 ثوانٍ.

عليك استخدام قيمة زمنية لـ expires، مثل:

expires: new Date(Date.now() + 1000 * 60 * 60 * 24) // 24 ساعة

استخدام قيمة زمنية للمؤشر index، مثل:

index: {
  expireAfterSeconds: 3600 // 1 ساعة
}

أو استخدام قيمة زمنية للمؤشر index، مثل:

index: {
  expireAfterSeconds: 3600 // 1 ساعة
}

أما بالنسبة لمشكلة التداخل، فهذا يحدث لأنك تقوم بإنشاء عنصر جديد في كل مرة تقوم فيها بإضافة منتج إلى السلة.

وحل هذه المشكلة عن طريق تحديث العنصر الموجود بدلاً من إنشاء عنصر جديد بتغيير الكود في index.js كما يلي:

if (cart) {
  var indexOfProduct = -1;
  for (var i = 0; i < cart.selectedProduct.length; i++) {
    if (product_id === cart.selectedProduct[i]._id) {
      indexOfProduct = i;
      break;
    }
  }
  if (indexOfProduct >= 0) {
    // console.log(cart.selectedProduct[indexOfProduct]);
    cart.selectedProduct[indexOfProduct].quantity++;
    cart.selectedProduct[indexOfProduct].price += newproductPrice;
    cart.selectedProduct[indexOfProduct].price =
      Math.round(cart.selectedProduct[indexOfProduct].price * 100) / 100;
    cart.totalquantity++;
    cart.totalPrice += newproductPrice;
    cart.totalPrice = Math.round(cart.totalPrice * 100) / 100;
    cart.createAt = Date.now();
    Carts.updateOne({ _id: cartId }, { $set: cart })
      .catch((err) => { console.log(err) })
      .then((result) => {
        console.log('update:', result);
        console.log('cart-update: ', cart);
      })
  } else {
    cart.totalquantity++;
    cart.totalPrice += newproductPrice;
    cart.totalPrice = Math.round(cart.totalPrice * 100) / 100;
    cart.selectedProduct.push(newProduct);

    cart.createAt = Date.now();
    Carts.updateOne({ _id: cartId }, { $set: cart })
      .catch((err) => { console.log(err) })
      .then((result) => {
        console.log('add:', result);
        console.log('cart-add: ', cart);
      })
  }
}

من أجل تحديث العنصر الموجود في حالة وجوده، أو إنشاء عنصر جديد إذا لم يكن موجودًا.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

ربما هذه الميزة قيد التطوير، أو أنه تم تحديثها و لم أعرف ما هو هذا التحديث.
على كل حال تم ضبط زمن الصلاحية و دون مشاكل بدون استخدام هذه الميزة . احتجت لأكواد أكثر لكن الحل بسيط.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...