发布到对象数组

时间:2019-05-31 16:11:43

标签: javascript node.js express mongoose routes

如何在此处正确发布数据。

我一直遇到错误,我无法成功将数据插入user.SavedMachines.Iduser.SavedMachines.Date中。

我也尝试过user.SavedMachines.Id = req.body.SavedMachinesIduser.Savedmachines.Date = Date.now(),但仍然遇到错误。

有人会知道如何成功插入数据吗?谢谢

//My Route:
router.route('/')
  .post((req, res) => {
    let user = new User();
    user.FirstName = req.body.FirstName;
    user.LastName = req.body.LastName;
    user.Email = req.body.Email;
    user.UserName = req.body.UserName;
    user.Password = req.body.Password;
    user.AdminRole = req.body.AdminRole;
    user.SavedMachines.Id.push(req.body.SavedMachinesId);
    user.SavedMachines.Date.push(Date.now());
    user.DateCreated = Date.now();
    user.LastUpdated = Date.now();

    user.save((err) => {user
      if (err) {
        res.send(err);
      } else {
        res.json({ message: 'User successfully added!'});
      }
    });
  })

// My Model Schema:
const UserSchema = new mongoose.Schema({
    FirstName: {
        type: String,
        default: ''
    },
    LastName: {
        type: String,
        default: ''
    },
    Email: {
        type: String,
        default: ''
    },
    UserName: {
        type: String,
        required: true,
        unique: true
    }, 
    Password: {
        type: String,
        required: true,
        bcrypt: true
    },
    AdminRole: {
        type: Boolean,
        default: false
    },
    SavedMachines: [{
        Id: {
            type: String,
            default: ''
        },
        Date: {
            type: Date,
            default: ''
        }
    }],
    DateCreated: {
        type: Date,
        default: ''
    },
    LastUpdated: {
        type: Date,
        default: Date.now
    }
});

1 个答案:

答案 0 :(得分:0)

我想通了

user.SavedMachines.push({Id: req.body.SavedMachinesId, Date: Date.now()});