Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

node.js - How to add an array to array field and the whole array must contain unique elements?

I want to carry out some as follows in MongoDB using Mongoose, is it possible?

const id = "5fjsjbvjbsdvjhkn6763287";
const arr = ["Hello", "World"]

await User.findByIdAndUpdate(
    id,
    {
        $addToSet: {
            arrayField: arr
        }
    }
);

Basically, adding an array to an array field and making sure the array is of unique elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The $each modifier is available for use with the $addToSet operator,

const id = "5fjsjbvjbsdvjhkn6763287"; 
const arr = ["Hello", "World"];
await User.findByIdAndUpdate(id,
  {
    $addToSet: {
      arrayField: { $each: arr }
    }
  }
);

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...