findOneAndUpdate on mongoose 更新文档内的数组或创建新文档

问题描述

我有这个架构

import mongoose from 'mongoose'

const logSchema = mongoose.Schema({
  fair: {
    type: mongoose.Schema.Types.ObjectId,ref: 'Fair',required: true
  },email: {
    type: String,unique: true,required: true,},user: {
    name: {
      type: String,others: {
      type: String,}
  },action: [{
    type: {
      type: String,title: {
      type: String,actionDate: {
      type: Date,default: Date.Now(),}
  }],createdAt: {
    type: Date,}
})

logSchema.index({ email: 1 })

export default mongoose.model('Log',logSchema)

现在我想做的是更新动作数组。像这样

Log.findOne({
    email: req.body.email
  })
    .then( log => {                  
      const newAction = {
        type: req.body.action.type,title: req.body.action.title,others: req.body.action.others
      }

      // Add to action array
      log.action.unshift(newAction);

      log.save()
        .then( log => {
          res.status(200).json(log);
        });
    })
    .catch( err => console.log(err));
});

当文档不存在时,我想创建一个与此类似的新文档

const log = {
      fair: req.headers['fair-api-key'],email: req.body.email,user: {
        name: req.body.user.name,others: JSON.stringify(req.body.user.others)
      },action: {
        type: req.body.action.type,others: JSON.stringify(req.body.action.others)
      }
    }

    const newLog = new Log(log)

    try {
      await newLog.save()

      res.status(201).json(newLog)
    } catch (error) {
      res.status(409).json({ message: error.message })
    }

我已经研究并找到了 findOneAndUpdate mongoose 方法,但我无法让它工作。 我想做这样的事情,因为当文档已经存在时,我不希望能够更改 user.name 或 user.others。 创建后,唯一应该可以更新的是动作数组。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)