【问题标题】:How do i remove a certain value from array in mongodb(mongoose model)如何从 mongodb 中的数组中删除某个值(猫鼬模型)
【发布时间】:2021-09-03 10:54:09
【问题描述】:

我正在做一个项目来插入和删除房间中的几个人 以下是我的架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const roomSchema=new Schema({
    Room_number:{
                   type:String,
                   required:true
                   },
    Roommates:{
                   type:Array,
                   default:[]
                   },
    Allocated: {
                    type:Boolean,
                    default:false
                     },
    Occupied:  {
                     type:Boolean,
                     default:false
                    },
    Batch:{
                     type:String
                    } ,
    position:{
                     type:String
                    }                                                               

},{
    versionKey: false // You should be aware of the outcome after set to false
})


var Room = mongoose.model('room', roomSchema);

module.exports = Room;

在这里你可以看到“Roommates”是一个数组,其中包含居住在该房间的人的姓名,例如 ["user1","user2","user3"] 所以我需要从数组中删除某个用户,但我没有得到一个 mongodb 命令来查找和更新它,我知道推送和拉取但我不知道如何在单个命令中从数组中删除特定值,我可以执行 for 循环并找到值,但我对更新某个文档的命令有疑问。

【问题讨论】:

  • 是否需要在所有文档中删除 Roommates 中的用户,或者在某些条件下过滤文档?
  • 是的,我想删除某个房间中的某个用户
  • @bhaginath 不,不是这样,我知道如何删除单个文档,但问题是如何删除数组中的一个名称。
  • @AshwinJoshy 您能否以 json 格式发布示例数据和预期数据。

标签: node.js arrays mongodb mongoose


【解决方案1】:

正确答案是

 Room.updateOne({ Room_number:room,Roommates:"Value i wanna find and delete or update" },{ $set: { "Roommates.$" :"here it find the firsts occurence in array and we can update by declaring here" } })

因为这是 updateOne ,所以数组中只有 1 个名称会被更新。 Roommates.$ 将在 Roommates 数组中找到第一次出现的结果

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2013-11-07
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2017-07-05
    • 2018-05-28
    • 2017-03-28
    相关资源
    最近更新 更多