app.post("/admin/editAssignedTask/:id", (req, res) => {
Task.findById(req.params.id, (err, task) => {
task.title = req.body.title;
task.priority = req.body.priority;
task.date = new Date(req.body.date);
task.description = req.body.description;
if (req.body.assignTo) {
console.log(req.body.assignTo);
if (typeof req.body.assignTo == "string") {
task.assignedTo = [...task.assignedTo, req.body.assignTo];
Staff.find({ _id: req.body.assignTo }, (err, staff) => {
console.log(staff);
});
Staff.updateOne(
{ _id: req.body.assignTo },
{ $set: { $push: { todo: req.params.id } } },
(err, up) => {
console.log(up);
}
);
上面的代码staff.find()返回
[ { todo: [ 5cc44b02abde080691893e41, 5cc46186db0195071f117808 ],
completed: [],
_id: 5cc34724ab9d2d231642f925,
name: 'gokul',
mailId: 'gokul',
__v: 12 } ]
但是staff.updateOne()返回 {ok:0,n:0,nModified:0} 这里n为0,这意味着没有对象匹配。 为什么会这样?
下面是Staff模式
var userSchema = new mongoose.Schema({
name: String,
mailId: String,
todo: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Task"
}
],
completed: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Task"
}
]
});
答案 0 :(得分:0)
更改
app.get("/api/shorturl/:shorturl",function(req,res){
let url=req.params.shorturl;
console.log(req.params);
console.log(req.url);
if(url===""){
res.send("no urls ");
}
try{
url=parseInt(url);
if (url>0 && url<=urls.length){
res.redirect(urls[url],301);
}
else{
res.send("we don't have this url");
console.log(url);
}
}
catch(err){
res.send("error occured");
}
});
到
Staff.updateOne(
{ _id: req.body.assignTo },
{ $set: { $push: { todo: req.params.id } } },
(err, up) => {
console.log(up);
}
);
1)不要使用$ set来推或拉数组元素。
2)由于在架构中,属性“ todo”是对象ID的数组而不是字符串,因此我们需要使用mongoose.Types.ObjectId()明确将字符串转换为对象ID。