在mongoDB上添加带有迁移的字段

时间:2018-12-13 11:05:40

标签: node.js mongodb mongoose migration

所以我试图将一个新字段迁移到mongoDB集合。 新字段是一个充满对象的数组。 迁移运行成功,并且在以下情况下甚至显示新字段: 寻找集合。 当我尝试向此字段添加数据时出现问题-它表明 字段未定义。 该如何解决这个问题?

迁移代码:

exports.up = async function(db) {
await db
    .collection('useractions')
    .update({}, {
      $set: {
        history: []
      }
    }, {multi: true, upsert: false});
};

用于填充新字段的代码:

const bookId = req.body.bookId;
const timestamp = req.body.timestamp;
const userId = req.body.userId;
const container = {bookId, timestamp};
UserAction.update(
  { userId },
  {$set: { history: container}},
  (err, cb) => {
  if(err)next({error: err});
    res.status(200).json({
      cb
    })
  })

编辑: 架构:

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

const userActionModel = new Schema({
  userId: {
    type: String
  },
  likes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Podcast',
    default: []
  }],
  tags: {
    type: [String],
    default: []
  },
  orderedBook: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Show',
    default: []
  }]
})
module.exports = mongoose.model('userAction', userActionModel);

0 个答案:

没有答案