簡體   English   中英

將數據推入貓鼬模型數組?

[英]Pushing data into Mongoose Model array?

嗨,我正在嘗試將字符串推入貓鼬數組中。 但是它沒有更新。

我的模特是

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);
                }
            });

我嘗試了兩種方法,但顯示為空數組。 而且,如果我每次運行此路線時,其中已經有數據就會被刪除。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM