简体   繁体   中英

How to remove an array element from Mongodb

I'm new to MEAN stack. I'm trying to implement this and this . I'm using $pull . But they ain't working maybe because my structure in mongodb is different from theirs. So let me first show you that:

在此处输入图片说明

downvoters is an string array that contains userids who downvoted that particular article. Lets say the person on downvoters[2] ie 53et853rf later upvoted this article.Then his userid should be removed from downvoters list. Here is my code:

api.js

router.put('/update-upvotes', (req, res) => {
  let articleData = req.body;
  ...
  Article.update(
    {articleid: '5p4aqbryi'},
    { $pull: { downvoters: '53et853rf' } }
  );
  Article.findOneAndUpdate(
    {articleid: '5p4aqbryi'},
    {upvotes: articleData.upvotes, upvoters: articleData.upvoters}, useFindAndModify=false,
    (error, user) => {
      if(error) {
        ...
      }
      else {
        ...
      }
    })
   })

But that id is not deleted. There's no error or warning on console. Please correct me.

And here is the schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
  articleid: String,
  title: String,
  content: String,
  date: String,
  contributor: String,
  upvotes: Number,
  upvoters: [],
  downvotes: Number,
  downvoters: []
})
module.exports = mongoose.model('article', articleSchema, 'articles');

PS: Let articleId and downvoter id be hardcoded now. I'll make them dynamic later.

Both upvoters and downvoters are String arrays so your Mongoose schema should look like below:

const articleSchema = new Schema({
    articleid: String,
    title: String,
    content: String,
    date: String,
    contributor: String,
    upvotes: Number,
    upvoters: [String],
    downvotes: Number,
    downvoters: [String]
});

You should also keep in mind that update() is an asynchronous operation which needs to be awaited or handled as Promise so:

let opResult = await Article.update(
    {articleid: '5p4aqbryi'},
    { $pull: { downvoters: '53et853rf' } }
);

or

Article.update(
        { articleid: '5p4aqbryi' },
        { $pull: { downvoters: '53et853rf' } }
    ).then(opResult => console.log(opResult));

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