我想获取 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/