javascript - 为什么 save 方法在 find 方法回调中不起作用?

标签 javascript node.js mongodb mongoose

我想获取 MongoDB 中最后插入的 _id,然后插入一个比上一个文档增加 _id 的新文档并保存它。 我编写此代码,它只获取最后一个 _id 但不保存文档

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);
               });
          }
     }

我的模块是

   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;

最佳答案

我真的认为你应该尝试像这样重写这段代码:

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));
  });

如果我没有记错的话 .save() 方法不会返回保存的文档,但即使它返回,如果保存时出现任何错误,您的代码也不会停止,因为您 假设“!err”做“你的事”。 JavaScript 不会关心是否发生错误并且您不会抛出它,因此您必须记录它以查看是否有任何错误。

关于javascript - 为什么 save 方法在 find 方法回调中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195733/

相关文章:

javascript - 通过 JavaScript 直接访问 MongoDB

php - 通过表单重定向而不给出错误

mongodb 单个操作中的多个聚合

java.lang.IllegalArgumentException : Invalid reference performing aggregation in MongoDB 异常

node.js - 带有 NodeJS 的 Google App Engine 502(坏网关)

javascript - Node.js:启动 pg.Pool()

javascript - 如何对无序数组进行深度比较?

javascript - 将类添加到函数 goForit()

javascript - 无法读取 null 的属性 'getElementById'

javascript - Angularjs $anchorScroll 在 ng-view 中不工作