简体   繁体   中英

How do I call remove() within mongoose query .find()?

I am querying a whole Mongodb collection called 'orders' with Mongoose. I then get the difference in days between order creation and the current date. When it has been a certain amount of days, I want to delete the document(order) from the db.

I am iterating over the orders in a for loop so when the loop finds an order with x amount of days difference, I am simply trying to call 'orders[i].remove()'. This is toward the bottom of the provided code block.

I have noticed that the 'remove()' method is on the Model.prototye and not the Document.prototype. But I have seen other code blocks where it is recommended to call 'remove()' within the 'find()' query.

Order.find({},'-_id -line_items -shipping_lines', function(err, orders) {
        if(err) {
            console.log(err);
        }
        for(i = 0; i < orders.length; i++) {
            // Taken from Punit Jajodia https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
            const dateOfOrder = orders[i].date;
            const now = new Date();
            const datefromAPITimeStamp = (new Date(dateOfOrder)).getTime();
            const nowTimeStamp = now.getTime();

            const microSecondsDiff = Math.abs(datefromAPITimeStamp - nowTimeStamp );
            // Number of milliseconds per day =
            //   24 hrs/day * 60 minutes/hour * 60 seconds/minute * 1000 msecs/second
            const daysDiff = Math.floor(microSecondsDiff/(1000 * 60 * 60  * 24));

            console.log(daysDiff);

            // If it is exactly 15 days from the triggering order, post the new order
            if (daysDiff === 15) {

                // ?consumer_key=${process.env.CONS_KEY}&consumer_secret=${process.env.CONS_SEC}

                //console.log(orders[i]);

                axios.post(baseUrl + `/orders?consumer_key=${process.env.CONS_KEY}&consumer_secret=${process.env.CONS_SEC}`, orders[i])
                .then(function (response) {
                    console.log(response.data);

                })
                .catch(function (error) {
                    // handle error
                    console.log(error.response.status);
                    // console.log(error);
                })
                .then(function () {

                });
            }

            if (daysDiff === 0) {
                //Remove orders that are 25 days old from the db
                orders[i].remove(function(err,result) {
                    if(err) {
                        console.log(err);
                    }
                    console.log(result);
                });
            }
        }
    });

I expected the document to be deleted when the if statement is truthy. But I get this error "message: 'No _id found on document!', name: 'MongooseError'" Im also looking at the orders in mlab and there is definitely an '_id' on them.

I guess your remove query is not in proper format. Try once as below:

        if (daysDiff === 0) {
            //Remove orders that are 25 days old from the db
            Order.remove({_id: orders[i]._id },function(err,result) {
                if(err) {
                    console.log(err);
                }
                console.log(result);
            });
        }

For example: to remove specific documents from the orders collection where the _id field equals to "something", works like below.

db.users.remove( { _id : "something" } )

Well. Here is the biggest facepalm of the last two days:

Within my .find() Query I was purposefully (accidentally) leaving out the _id with:

Order.find({},'-_id -line_items -shipping_lines', function(err, orders) { ...

That caused orders[i]._id to be undefined within my for loop. We live to code another day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM