用户使用Mongoose MongoDB进行的更新推送不起作用。

huangapple go评论57阅读模式
英文:

user updates using Mongoose mongodb push not working

问题

我正在尝试使用 MongoDB Mongoose MongoDB push 来更新一个实体,以便将 dcrLocations 数组中的 dcrlocation 实体推送到其中。

这是来自 MongoDB 服务器的响应

{
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

这是我的模型代码

import mongoose from "mongoose";

// 用户模式
const UserSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  username: {
    type: String,
  },
  email: {
    type: String,
    required: true,
    lowercase: true,
    trim: true,
    unique: true,
    index: true,
  },
  password: {
    type: String,
    required: true,
    trim: true,
  },
  hasSubscription: {
    type: Boolean,
    default: false,
  },
  dcrLocations: [
    {
      dcrLocationId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'DCRLocation',
      },
    },
  ],
},
{
  toJSON: {
    transform(doc, ret) {
      delete ret.password;
      delete ret.__v;
      delete ret.createdAt;
      delete ret.updatedAt;
    },
  },
  timestamps: true,
});

UserSchema.index({ email: 1, phone: 1 });

export default mongoose.model("User", UserSchema);

这是我的控制器代码

import { User } from "../../path/to/model.js";
import { ObjectID as ObjectId } from "mongodb";

function functionName() {
  return {
    AssDCRLoToUsr: async (req, res) => {
      try {
        const { dcrLocationId } = req.body;
        console.log(dcrLocationId);

        const userToUpdate = await User.updateOne(
          { _id: req.params.id },
          {
            $push: {
              dcrLocations: {
                dcrLocationId: new ObjectId(dcrLocationId),
              },
            },
          }
        );
        console.log(userToUpdate);
        res.json(userToUpdate);
      } catch (error) {
        console.error(error);
        res.json(false);
      }
    },
  };
}

export { functionName };

有关如何使这个工作的建议吗?我已经与它斗争了一段时间了。

英文:

I am trying to use MongoDB Mongoose MongoDB push to update an entity such that the dcrLocations array gets the dcrlocation entity pushed into it

This is my response from the MongoDB server

{
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

Heres my model code
import mongoose from "mongoose";

//User Schema
const UserSchema = new mongoose.Schema({
            firstName: {
                type: String,
                required: true,
            },
            lastName: {
                type: String,
                required: true,
            },
            username: {
                type: String,
            },
            email: {
                type: String,
                required: true,
                lowercase: true,
                trim: true,
                unique: true,
                index: true,
            },
            password: {
                type: String,
                required: true,
                trim: true,
            },
            hasSubscription: {
                type: Boolean,
                default: false
            },
        dcrLocations: [
                    {
                        dcrLocationId: {
                            type: mongoose.Schema.Types.ObjectId,
                            ref: 'DCRLocation'
                        }
                    },
                ]
        },
        {
            toJSON: {
                transform(doc, ret) {
                    delete ret.password,
                        delete ret.__v,
                        delete ret.createdAt,
                        delete ret.updatedAt
                }
            }
            ,
            timestamps: true,

        }
    )
;

UserSchema.index({email: 1, phone: 1})

export default mongoose.model("User", UserSchema);

Heres my controller code

 import {User} from "../../path/to/model.js";
import {ObjectID as ObjectId} from "mongodb";

    
    function functionName() {
        return {
            AssDCRLoToUsr: async (req, res) => {
                try {
                    const {dcrLocationId} = req.body;
                    console.log(dcrLocationId)
    
                    const userToUpdate = await User.updateOne(
                        {_id: req.params.id},
                        {
                            $push: {
                                dcrLocations: {
                                    dcrLocationId: new ObjectId(dcrLocationId)
                                }
                            }
                        }
                    );
                    console.log(userToUpdate)
                    res.json(userToUpdate)
                } catch (error) {
                    console.error(error)
                    res.json(false)
                }
            },
    
    
        }
    }
    
    export {functionName};

Any advice on how I can make this work? I have been battling with it for some time now

答案1

得分: 1

$addToSet 用于在数组中添加唯一元素。

import { User } from "../../path/to/model.js";
import { ObjectID as ObjectId } from "mongodb";

function functionName() {
    return {
        AssDCRLoToUsr: async (req, res) => {
            try {
                const { dcrLocationId } = req.body;
                console.log(dcrLocationId);

                const userToUpdate = await User.updateOne(
                    { _id: req.params.id },
                    {
                        $addToSet: {
                            dcrLocations: {
                                dcrLocationId: new ObjectId(dcrLocationId)
                            }
                        }
                    }
                );
                console.log(userToUpdate);
                res.json(userToUpdate);
            } catch (error) {
                console.error(error);
                res.json(false);
            }
        }
    };
}

export { functionName };
英文:

try this

$addToSet is used to add unique element in array

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import {User} from &quot;../../path/to/model.js&quot;;
import {ObjectID as ObjectId} from &quot;mongodb&quot;;

    
    function functionName() {
        return {
            AssDCRLoToUsr: async (req, res) =&gt; {
                try {
                    const {dcrLocationId} = req.body;
                    console.log(dcrLocationId)
    
                    const userToUpdate = await User.updateOne(
                        {_id: req.params.id},
                        {
                            $addToSet: {
                                dcrLocations: {
                                    dcrLocationId: new ObjectId(dcrLocationId)
                                }
                            }
                        }
                    );
                    console.log(userToUpdate)
                    res.json(userToUpdate)
                } catch (error) {
                    console.error(error)
                    res.json(false)
                }
            },
    
    
        }
    }
    
    export {functionName};

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 22:37:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75058831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定