删除使用mongoose返回错误的子文档?
我想删除我的collections的所有子文件。
mongoose模式:
//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"
使用$unset
运算符,它使用findOneAndUpdate()
方法删除products
字段。 使用传统方法首先用findById()
检索文档只能使用有效的ObjectId
,在你的情况下,你只提供一个非ObjectId
string,因此是错误的。
router.post('/delete',function (req,res) { var providerId = req.body.providerId; model.Shops.findOneAndUpdate( { "providerId": providerId }, { "$unset": { "products": "" } }, { "new": true } function(err, doc) { console.log(doc) // returns modified doc here... res.json({"msg": "Field deleted"}); } ); });
如果你想保留数组字段,但删除它的所有元素,使用$set
as
router.post('/delete',function (req,res) { var providerId = req.body.providerId; model.Shops.findOneAndUpdate( { "providerId": providerId }, { "$set": { "products": [] } }, { "new": true } function(err, doc) { console.log(doc) // returns doc with empty products here... res.json({"msg": "Products deleted"}); } ); });
这是因为您将shopSchema中的“providerId”保存为Stringtypes,即使它是mongoose对象。 所以,比较stringtypes和mognoose ObjectIdtypes会产生一个转换错误。
相反,做这个,
var shopSchema = new Schema({ "providerId" : { type : Schema.ObjectId ref : schema which they are a reference to}, "provider" : {type : String}, "products" : [pdtSchema] },{collection:"shopdetails"});
但是,我认为如果providerId引用一个商店Id,那么它应该只是_id。
model.findById()适用于_id