简体   繁体   中英

Update nested subdocument array in mongoose

I am currently learning nodejs. I want to update my mongoose model.

Here is the model:

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    }, 
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    lists: [{
        listname: String,
        listitems: [{item: String}]
    }]
});

The model currently has the name, password and email but the lists array is empty, now I want to update list array and add a new listname. What should be the query for this? currently i am using this:

router.post('/NewList',(req,res)=>{
    res.send('ok');
    const username = req.body.createListbtn;
    const title = req.body.newListTitle;
    console.log(title);
    User.updateOne({name:username}, {$set:{"lists.listname": title}});
});

You should do something like,using $addToSet

UserSchema.updateOne({name:"name"},{ $addToSet: { lists: [{listname:"something",listitems:["listitems"]},{listname:"something",listitems:["listitems"]}] })

The first part is the condition in update query,you can remove it to update all docs

UserSchema.update({},{ $addToSet: { lists: [{listname:"something",listitems:["listitems"]},{listname:"something",listitems:["listitems"]}] })

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