简体   繁体   中英

Why doesn't save method work inside find method callback?

I want to get the last inserted _id in the MongoDB and then insert a new document that has incremented _id from the last one and save it. I Write this code it just gets the last _id but it doesn't save the document

Product.find({}, function(err , result)
    {
           if(!err)
           {
               result.forEach((p)=>{
                   count = p._id;
               });
               var product = new Product();
               product._id = count++;
               product.Name  = req.body.Name;
               product.Price = req.body.Price;
               product.Quantity = req.body.Quantity; 
               product.Imgsrc = req.body.Imgsrc;
               product.Cat_id = req.body.Cat_id;
               product.save((err, result)=>
               {
                    if(!err)
                    console.log(result);
               });
          }
     }

my module is

   const mongoose = require('mongoose');

var ProductSchema = new  mongoose.Schema({

    _id : {type : Number } , 
    Name : {type : String} , 
    Price : {type :Number} ,
    Quantity  : {type : Number} , 
    Imgsrc : {type : String} , 
    Cat_id :   { type: Number , ref : 'Categorys' } 
});


var product = mongoose.model("Product", ProductSchema, "Product")

module.exports = product;

I really think you should try re-writing this piece of code like this:

Product.find({}, {sort: {_id: -1}, limit: 1}, function(err, result) {
    if(err) {
         console.log(err)
    }

    var count = result[0]._id;
    var product = new Product({
         product._id: ++count,
         ...req.body
    });

    product.save(err => console.log(err));
  });

If I'm not mistaken .save() method do not return the saved document, but even if it does, your code do not stop if there is any errors on saving because you assume "!err" to do "you stuff". JavaScript will not care if some error occurs and you do not throw it, so you must log it to see if there is any.

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