mongoose nodejs如何从数据库和用户项目数组中删除项目

时间:2018-10-01 13:13:30

标签: node.js mongodb mongoose mongoose-schema

我的应用程序有一个包含一系列项目的用户,当我单击以打开一个项目时,我有一个“删除”按钮,因此可以删除该项目(按其ID)。那行得通,但是我的问题是: 我可以从数据库中删除项目,但不能从保留项目ID的用户数组项目中删除该项目。

这是我的用户架构:

let mongoose = require("mongoose");


let passportLocalMongoose = require("passport-local-mongoose");


let UserSchema = new mongoose.Schema({

   username: String,
   password: String,
   companyname: String,
   companyimageURL: String,
   projects: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project'
  }] 
});


UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

我的项目架构:

let mongoose = require("mongoose");

let projectSchema = new mongoose.Schema({

   projectname: String,
   typeofproject: String,
   imageURL: String,
   dateMonthFrom: String,
   dateYearFrom: String,
   dateMonthTo: String,
   dateYearTo: String,
   tasks: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Tasks'    
   }],
   user: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
   }] 
})

module.exports = mongoose.model('Project', projectSchema);

和我的服务器端:我认为我全都错了!这是我尝试通过按ID和删除找到该项目,然后按ID和更新找到用户的方式来做的,但这不起作用。

//Delete Project
app.delete('/dashboard/project/:id/edit', (req, res) => {
let id = req.params.id;
let userid = req.user._id;


let project = {
    projectname: req.body.projectname,
    typeofproject: req.body.typeofproject,
    imageURL: req.body.imageURL,
    dateMonthFrom: req.body.dateMonthFrom,
    dateYearFrom: req.body.dateYearFrom,
    dateMonthTo: req.body.dateMonthTo,
    dateYearTo: req.body.dateYearTo,
}; 

Project.findByIdAndDelete(id, (err) =>{
    if(err){
        console.log(err);
    }

    User.findByIdAndUpdate(userid, {$set:project}, {new: true},(err) => {
            if(err){
                 console.log(err)
            }
            console.log('Project Deleted: ' + id)
            res.redirect('/dashboard#/projects');
         });
    });
 };  

非常感谢您!

2 个答案:

答案 0 :(得分:1)

您可以使用$pull运算符。访问this页面以了解更多详细信息。

您的user更新查询应如下所示:

User.findByIdAndUpdate(
  userid,
  { $pull: { projects: id } },
  { new: true }
);

答案 1 :(得分:0)

现在可以了!我的结果:

app.delete('/dashboard/project/:id/edit', (req, res) => {
    let id = req.params.id;
    let userid = req.user._id;



Project.findByIdAndDelete(id, (err) =>{
    console.log('deleting project', id)
    if(err){
        console.log(err);
    }

        User.findByIdAndUpdate(
            userid, 
            { $pull: { projects: id} }, 
            { new: true },(err) => {
                if(err){
                     console.log(err)
                }

                console.log('Project Deleted: ' + id)
                res.redirect('/dashboard#/projects');
       })
   })
};