我需要从我的模型中取出数组,过几天从中删除并在其他几天推送到它。它看起来像 deleteAndUpdate
。
总结:
我需要从数据库中取出 Car
。取 reserved
属性(它是一个数组),然后从给定列表的 reserved
天中删除,然后从其他给定列表中添加到 reserved
天。
我的模型外观:
const CarSchema = mongoose.Schema({
mark:{
type: String,
required: true,},
model:{
type: String,
required: true,},
price:{
type: Number,
required: true,},
available: {
type: Boolean,
required: true,},
reserved:{
type:[Date],
},
pic_1:{
type:String,
required:true,
},
pic_2:{
type:String,
required:true,
},
},
{ collection: 'cars' }
)
我乘车经过:var car= await Car.findById(carID);
然后我需要这样做:
car['reserved'].deleted(old_days);
car['reserved'].push(new_days;
car.save();
有人可以帮我吗?
答案 0 :(得分:1)
要从数组中删除旧项目,您可以使用 $pull
car.update(
{ _id: carID },
{ $pull: { 'reserved': old_days } }
);
您可以使用 $unset 取消设置数组中的值(将其设置为 null),但不能完全删除它。
要将项目 new_days 添加到数组中,您可以使用 $push 或 $addToSet
car.update(
{ _id: carID },
{ $push: { 'reserved': new_days } }
);
答案 1 :(得分:1)
更新不能在同一个字段中同时允许多个操作,它会抛出多个写入错误并且会在你的字段中产生冲突,
如果你想通过定期更新查询来做到这一点,你必须单独做 2 个查询,
$pullAll
,对于单个你可以使用$pull
var old_days = [new Date("2021-04-24"), new Date("2021-04-25")];
await Car.updateOne({ _id: carID }, { $pullAll: { reserved: old_days } });
$push
与 $each
一起使用,对于单个您可以仅使用 $push
,立>
var new_days = [new Date("2021-04-26"), new Date("2021-04-27")];
await Car.updateOne({ _id: carID }, { $push: { reserved: { $each: new_days } } });
如果您正在寻找单个查询,您可以从 MongoDB 4.2 开始使用 update with aggregation pipeline,
$filter
迭代保留数组的循环并删除过去$concatArrays
将保留数组与新天数连接起来var old_days = [new Date("2021-04-24"), new Date("2021-04-25")];
var new_days = [new Date("2021-04-26"), new Date("2021-04-27")];
await Car.updateOne(
{ _id: carID },
[{
$set: {
reserved: {
$filter: {
input: "$reserved",
cond: { $not: { $in: ["$$this", old_days] } }
}
}
}
},
{
$set: {
reserved: {
$concatArrays: ["$reserved", new_days]
}
}
}]
);