Conditionally include fields in mongoose .save()

时间:2018-09-18 20:04:17

标签: mongodb mongoose

Is it possible to add a key to a .save() argument conditionally? Something like this:

Posts.save(
  dbPost,
  {
    _id: new mongoose.Types.ObjectId(),
    title: args.title,
    content: args.content,
    events: {
      created_on: new Date(),
      (() => {
        if(args.published) { return {published_on: new Date()}}
      })
    }
  }
);

Of course, the above script doesn't work (it throws a syntax error) but it hopefully illustrates my objective. I need to add the field published_on along with its value to the payload, but only if the args.published is set to true.

0 个答案:

没有答案