将数据推入猫鼬模型数组?

时间:2019-04-12 11:55:17

标签: javascript arrays node.js mongodb mongoose

嗨,我正在尝试将字符串推入猫鼬数组中。但是它没有更新。

我的模特是

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  project:{
    type: new mongoose.Schema({
      name: {
        type: [String], //tryxing to push data here
        required: true,
        minlength: 2,
        maxlength: 50
      }
    }),

  },
  isAdmin: Boolean
});

在我正在执行的代码中

router.put('/addProject', auth, async (req, res) => { //To update password
user = await User.findByIdAndUpdate(req.user._id,{project:{$push :{name:req.body.projectname}},new :true});

        /*********OR********/
        User.findOneAndUpdate(
           { _id: req.user._id }, 
           {project:{ $push: { name: req.body.projectname  } }},
          function (error, success) {
                if (error) {
                    console.log(error);
                } else {
                    console.log(success);
                }
            });

我尝试了两种方法,但是显示出空数组。并且如果我每次运行此路由时都已经删除了数据。 谢谢

1 个答案:

答案 0 :(得分:1)

您需要将projectname字段更改为:

project:{
    name: [{
        type: String, // and not `type: [String]`
        required: true,
        minlength: 2,
        maxlength: 50
      }
    }]
},

最终方案为:

// user.model.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  },
  email: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 1024
  },
  project:{
    name: [{
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
      }]
  },
  isAdmin: Boolean
});

export default User = mongoose.model('User', userSchema);

然后在您的控制器中:

import User from './user.model';

router.put('/addProject', auth, async (req, res) => {
user = await User.findByIdAndUpdate(req.user._id, 
  { $push: { 'project.name': req.body.projectname }, { new: true });
...

编辑:要从数组中删除元素,请使用$pull

await User.findByIdAndUpdate(req.user._id, 
  { $pull: { 'project.name': req.body.projectname }, { new: true });
...