Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove document objectid only in populated array in mongoose

I'm having a really difficult time trying to remove the objectids from an array using a populated query.

this is my Schema

var userSchema = new Schema({
  username: String,
  password: String,
  books: [{type: Schema.Types.ObjectId, ref: 'Book'}]
  }
);

var bookSchema = new Schema({
  bookid: {type:String, unique:true, required:true},
  imgURL: String,
  fortrade: Boolean
});

The problem is with the query shown below. it removes removes the book schema item when I only want it to remove the objectid in the books array.

users.findOne({'_id':userid}).populate('books').exec(function(usererr,userdata){
        if (usererr) return console.error(usererr);

        userdata.books.forEach(function(elm,idx){
            if(elm.bookid==_book.bookid){
                userdata.books[idx].remove();
            }
        })
    });
like image 832
chad schmidt Avatar asked Dec 18 '22 20:12

chad schmidt


1 Answers

If all you want to do is select the refernced fields in the output of the related object from .populate(), then simply supply the list of either the fields you want, or want to remove within the .populate() call:

users.findOne({'_id':userid})
    .populate('books',"-_id")
    .exec(function(usererr,userdata){
       // userdata contains related without the _id field
    });

So the second parameter there in the .populate() specifies the fields you want to select in the subsequent query. The - notation means to "exclude" the field, otherwise you need to specify a list of fields to specifically include.

This is basic MongoDB field "projection". One rule here is that you cannot "mix" both include or exclude. So either be explicit:

.populate('books','bookid imgURL forTrade')

Or just exlcude the "special" fields:

.populate('books', '-_id -__v')

where _id is the general "always included" primary key, and __v is the mongoose generated version key, which you also might not want in results.

Also see Limit Fields to Return in a Query from the core documentation, as well as the mongoose shortened syntax for this under .select().

like image 85
Blakes Seven Avatar answered Mar 08 '23 12:03

Blakes Seven