简体   繁体   中英

How to update only one property in MongoDB using Mongoose?

This is my model:

import mongoose from 'mongoose';

const UserData = new mongoose.Schema({
    additionalData: Array,
    name: String,
});
mongoose.model('UserData', UserDataSchema);
mongoose.set('useFindAndModify', false);

export default mongoose.model('UserData');

How can I update additionalData property of UserData model so for example another array is appended.

Let's say additional array is

[ 1, 2, 3]

You can use $addToSet

await UserData.update({name:"something"},{ $addToSet: { additionalData: [1,2,3] })

or

await UserData.updateOne({name:"something"},{ $addToSet: { additionalData: [1,2,3] })

If you have no condition do this,this will add to all documents

await UserData.update({},{ $addToSet: { additionalData: [1,2,3] })

If you want to remove multiple values from the array,use$pull

await UserData.update({},{ $pull: { additionalData: { $in: [ 1, 2,3 ] }}})

If you wish to remove single value

await UserData.update({},{ $pull: { additionalData:1 }})

If this is not what you mean, let me know in the comments, I'll edit the answer.

const newArray = [ 1, 2, 3];
const nameToUpdate = 'foo';
mongoose.model('UserData').updateMany({
    name: nameToUpdate
}, {$set: {
    additionalData: newArray
}});

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