简体   繁体   English

从mongodb中的嵌套文档数组中删除单个记录

[英]Delete a single record from an array of nested document in mongodb

I want to delete just one contact from the contacts array of a particular user from mongdb dynamically using nodejs 我想使用nodejs从mongdb中动态删除特定用户的联系人数组中的一个联系人

    {
    _id:ObjectId("532737785878v7676747788"),
    firstname:"Mark",
    lastname:"Anthony",
    email:"xyz@gmail.com",
    contacts:[
   {
    _id:ObjectId("678758478fr7889889)",
    firstName:"James",
    lastName:"Cole",
    phoneNo:"09746"
   },
  {
    _id:ObjectId("678758478fr7889889)"
    firstName:"Jane"
    lastName:"Doe"
    phoneNo:"12345"
   }
]
    }

I tried this: 我尝试了这个:

       User.updateOne(
       {email:'xyz@gmail.com', 'contacts._id':678758478fr7889889},
       { $pull : { contacts : { firstName:'Jane', lastName:'Doe',  phoneNo:'12345'} } },
       {multi:true},
       );

I am not getting any error messages and it's not deleting any contact 我没有收到任何错误消息,也没有删除任何联系人

Mongoose would use defined schema to create ObjectId's in DB while on writes but it would not use schema on _id(ObjectId's) for find queries, So you've to explicitly say that _id is an ObjectId(). 猫鼬会在写时使用已定义的架构在数据库中创建ObjectId,但不会在_id(ObjectId's)上使用架构进行查找查询,因此,您必须明确地说_id是ObjectId()。 Please have this in your code : 请在您的代码中输入:

const mongoose = require('mongoose'); // Ignore this if you've already imported.
const ObjectId = mongoose.Types.ObjectId;

// Assuming id is the value you've got in request.
User.updateOne(
   {email:'xyz@gmail.com', 'contacts._id':new ObjectId(id)},
   { $pull : { contacts : { firstName:'Jane', lastName:'Doe',  phoneNo:'12345'} } });


// you can do the same with `findOneAndUpdate` with options {new: true} which would return updated document, by default it would be false that meant to return old document.
User.findOneAndUpdate(
       {email:'xyz@gmail.com', 'contacts._id':new ObjectId(id)},
       { $pull : { contacts : { firstName:'Jane', lastName:'Doe',  phoneNo:'12345'} } }, {new : true});
db.collection.update({
        email:'xyz@gmail.com',
        contacts: {
            $elemMatch: {
                "_id": "678758478fr7889889"
            }
        }
    }, {
        $pull: {
            contacts: {
                _id: '678758478fr7889889'
            }
        }
    }

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM