我想刪除我的集合的所有子文檔。使用貓鼬刪除子文檔返回錯誤?
貓鼬模式:
//productSchema
var pdtSchema = new Schema({
"productId" : {type : String},
"product" : {type : String},
"item no" : {type : String},
});
var shopSchema = new Schema({
"providerId" : {type : String},
"provider" : {type : String},
"products" : [pdtSchema]
},{collection:"shopdetails"});
module.exports.Shops = mongoose.model('Shops',shopSchema);
module.exports.Products = mongoose.model('Products',pdtSchema);
我已經存儲了一個大部分集合內的數據,我需要刪除所有的產品(即整個pdtSchema
數據)。
代碼:
router.post('/delete',function (req,res) {
var providerId = req.body.providerId;
model.Shops.findById({"providerId" : providerId},function(err, doc) {
console.log(doc.products) // returns whole products here...
doc.products.remove();
doc.save(function(err,data){
res.json({"msg":"deleted"});
});
});
});
錯誤:
(node:16351) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: CastError: Cast to ObjectID failed for value "[Function]" at path "_id"
那是因爲你使用model.findById()函數,該函數_id工作給了一個錯誤,但是你用providerId嘗試它其中我們String類型的 –