首页 > 解决方案 > 将数据推送到 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);
                }
            });

我尝试了这两种方法,但它显示的是空数组。如果每次我运行这条路线时已经有数据被删除..谢谢

标签: javascriptarraysnode.jsmongodbmongoose

解决方案


您需要将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 });
...

推荐阅读