[英]Deleting subdocuments using mongoose returning error?
我想删除我收藏的所有子文档。
猫鼬模式:
//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
字符串,因此会出现错误。
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”保存为 String 类型,即使它是一个猫鼬对象。 因此,将字符串类型与 mognoose ObjectId 类型进行比较会产生转换错误。
而是这样做,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.