有一个控制器:
exports.chooseTransporter = (req, res, next) => {
const transporter = new Signup({
_id: req.params.signupId,
approved: req.body.approved
});
Signup.updateOne({ _id: req.params.signupId}, transporter).then(result => {
res.status(201).json({
message: "Signup updated!",
result: result
});
})
.catch(err => {
res.status(500).json({
message: "DB error!"
});
});
}
和模型:
const mongoose = require("mongoose");
const signupSchema = mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
cargoId: { type: mongoose.Schema.Types.ObjectId, ref: "Cargo", required: true },
truckIds: [{type: mongoose.Schema.Types.ObjectId, ref: "Truck", required: true }],
approved: { type: Boolean ,required: true },
finished: { type: Boolean ,required: true }
});
module.exports = mongoose.model("Signup", signupSchema);
创建注册后,我的集合如下所示:
{
"_id" : ObjectId("616eb5061aeeabc39184696d"),
"truckIds" : [
ObjectId("6131f12e8ed8b949f6752c59"),
ObjectId("6137150e1b92ae2bf762f87b")
],
"userId" : ObjectId("60868c31caafe530e7e2d04a"),
"cargoId" : ObjectId("614da0b0812a2f6169163d37"),
"approved" : false,
"finished" : false,
"__v" : 0
}
运行chooseTransporter方法并将approved设置为true后,我的truckIds数组包含0个元素,如下所示:
{
"_id" : ObjectId("616eb5061aeeabc39184696d"),
"truckIds" : [],
"userId" : ObjectId("60868c31caafe530e7e2d04a"),
"cargoId" : ObjectId("614da0b0812a2f6169163d37"),
"approved" : true,
"finished" : false,
"__v" : 0
}
提前感谢!
尝试更改updateOne
参数并仅指定approved
属性:
Signup.updateOne({ _id: req.params.signupId }, { approved: req.body.approved })
.then((result) => {
res.status(201).json({
message: 'Signup updated!',
result: result,
});
})
.catch((err) => {
res.status(500).json({
message: 'DB error!',
});
});