简体   繁体   中英

Mongoose how to update array from child to parent

I have following schema for Audio.

const AudioSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    uploaderId: {
        type: String,
        required: true
    }
});

Instead of referencing the User, I just store the User's _id as uploaderId.

In my User schema I also have audioFiles: [Audio] array for all audio files that user has uploaded.

const UserSchema = new mongoose.Schema({
    ...,
    audioFiles: [Audio]
});

When I try to update my AudioSchema from my REST Api, I can change all the properties and that works, but after saving this Audio model those changes doesn't affect the User model.

Now I created a new branch and try to change uploaderId to UserSchema . But I wonder is there a solution for this without referencing the UserSchema

I managed to do this with help of MongooseArray.prototype.pull method.

Steps for solving this problem is really easy.

First I get the User that is associated with AudioModel.uploaderId, then I used the user.audioFiles.pull() method. Correct code is below.

let user = await UserService.getUser(userId);

await user.audioFiles.pull({
    _id: audioId //audioId is the id which i'm trying to remove from array
});

await user.save();

I also added try-catch block to handle errors.

Anyone having this kind of issue can use the link below to get more information about MongooseArray.prototype.pull method.

Also you can check the other answers in this post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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