简体   繁体   中英

Remove an array value from mongodb collection document, sailsjs

I have an array like this on under user collection 在此处输入图片说明

How can i remove a single value from this array by using sails.js code

also i need to remove all post id from every users document if a post is deleted, is there any simplest and fastest way to remove from all documents too??

There are a couple of easy ways to do it if you're using the built-in ORM "Waterline", and they are basically equivalent.

The first is to run Model.update() and overwrite the array with the new value.

Model.update(id, { likes : [/* new array value */] }).then(...)

The other is to 1) find the object 2) pull the value off the array 3) save:

Model.findOne(id, function(err, document){
  if(err) // handle err case
  else {
    document.likes = document.likes.filter(value => value !== 'stringToRemove')
    document.save(function(err, saved){
      ... // do more stuff
    })
  }
})

Finally, unless you're using it for a very simple app, I cannot recommend using Waterline ORM with MongoDB. Save yourself a heap of headache and use Mongoose .

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