猫鼬:如何发布到架构内部的数组

时间:2020-04-16 11:51:55

标签: javascript mongoose

我有一个Company Schema,它将保存该公司的一些数据和一系列帖子。当用户提交帖子时,我使用护照对令牌进行解码并获取一些用户信息。在该用户信息中,有一个对象ID,该ID可让我找到该用户所属的公司。

所以现在我找到了用户所属的公司,我需要将提交的帖子保存到该公司内部的board_posts数组中

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BoardPostSchema = new Schema({
    name: {
        type: String
    }
});

const CompanySchema = new Schema({
    company_name: {
        type: String
    },
    board_posts: [BoardPostSchema],
});

module.exports = Company = mongoose.model('companies', CompanySchema);
router.post('/new-opportunity',  passport.authenticate('jwt', { 
    session: false 
}), (req, res) => {
    let user = req.user;
    let newPost = req.body;
    let companyId = user.company_id;

    const boardPost = {
        name: newPost.name
    };

    Company.find({'_id': companyId})
        .then(company => {
            // push boardPost into this company.board_posts array
        })
        .catch(error => {

        });
});

3 个答案:

答案 0 :(得分:1)

您可以使用$pushupdate

router.post('/new-opportunity',  passport.authenticate('jwt', { 
    session: false 
}), (req, res) => {
    let user = req.user;
    let newPost = req.body;
    let companyId = user.company_id;

    const boardPost = {
        name: newPost.name
    };

    Company.update({_id: user.company_id},{
         $push{
             //the things you want to add
         }
    });
});

希望这是您想要做的!

答案 1 :(得分:1)

findByIdAndUpdate的替代解决方案:

.skip(1)

或者,如果您只想更新状态,则可以使用updateOne

router.post("/new-opportunity", passport.authenticate("jwt", { session: false }), (req, res) => {
  let user = req.user;
  let newPost = req.body;
  let companyId = user.company_id;

  const boardPost = {
    name: newPost.name,
  };

  Company.findByIdAndUpdate(
    companyId,
    {
      $push: {
        board_posts: boardPost,
      },
    },
    {
      new: true,
    }
  )
    .then((company) => {
      console.log("Updated compay if found:", company);
      res.send(company);
    })
    .catch((error) => {
      console.log(error);
      res.status(500);
    });
});

答案 2 :(得分:0)

是的,您可以使用$pushfindOneAndUpdate运算符。如果您使用async/await方法,效果会更好。

router.post('/new-opportunity',  passport.authenticate('jwt', { 
   session: false 
}), async (req, res) => {
   let user = req.user;
   let newPost = req.body;
   let companyId = user.company_id;

   const boardPost = {
       name: newPost.name
   };

  let response = await Company.findOneAndUpdate({'_id': companyId}, {
     $push: {
        board_posts: "testword1"
     }
  },{ new: true })  //i set this to true so mongodb will return me the new updated document

  res.send(response);

});