Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

mongodb - Mongoose pull ObjectId from array

i'm trying to do a pretty simple operation, pull an item from an array with Mongoose on a Mongo database like so:

User.update({ _id: fromUserId }, { $pull: { linkedUsers: [idToDelete] } });

fromUserId & idToDelete are both Objects Ids.

The schema for Users goes like this:

var UserSchema = new Schema({
  groups: [],
  linkedUsers: [],
  name: { type: String, required: true, index: { unique: true } }
});

linkedUsers is an array that only receives Ids of other users.

I've tried this as well:

User.findOne({ _id: fromUserId }, function(err, user) {
  user.linkedUsers.pull(idToDelete);
  user.save();
});

But with no luck.

The second option seem to almost work when i console the lenghts of the array at different positions but after calling save and checking, the length is still at 36:

 User.findOne({ _id: fromUserId }, function(err, user) {
    console.log(user.linkedUsers.length); // returns 36
    user.linkedUsers.pull(idToDelete);
    console.log(user.linkedUsers.length); // returns 35
    user.save();
  });

So it looks like i'm close but still, no luck. Both Ids are sent via the frontend side of the app. I'm running those versions:

"mongodb": "^2.2.29",
"mongoose": "^5.0.7",

Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to explicitly define the types in your schema definition i.e.

groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }], 
linkedUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }]

and then use either

User.findOneAndUpdate( 
    { _id: fromUserId }, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);

or

User.findByIdAndUpdate(fromUserId, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...