简体   繁体   中英

Mongodb/Mongoose: Filling Array of ObjectIds (references)

I have a mongodb running (MEAN environment) with two collections (users and books). One of those collections (myusers) contains an array of Objectids (references to documents of books collection) as such:

var UserSchema = new Schema({
    [...],
    externalids: [{type: Schema.Types.ObjectId, ref: 'Books', required: false}]
    }, {collection: 'myusers'});

At runtime, I'd like to constantly fill that array (externalids) with ids of new book documents. This is how I do it:

var newBook = new Book({ ... });

        newBook.save(function (err){
                if (err){
                    //whatever  
                }else{
                    User.update({ _id: req.user._id }, { $set: { externalids: newBook._id }}, function(err){
                        //whatever       
                    });
                }
        }); 

Unfortunately, I can't use something like:

externalids: externalids.push(newBook._id)

I even tried:

User.update({ _id: req.user._id }, { $push: { externalids: newBook._id }}

But it wouldn't help either. Thus, the array always only contains one value (the latest) and won't be filled up. Is there a quick way to append more values? Would be nice if there was a quicker way than reading the array content first, storing it to a local temporary array, append the new value and write the entire array back... Cheers

Igor

Try $addToSet instead of $push to avoid duplicate id.

User.update({ _id: req.user._id }, { $addToSet : { externalids: newBook._id }}

What can be your issue is that you previously use $set to update an user. This will initially create externalids as string, not array, hence you cannot use $push/$addToSet on externalids afterwards. To correct that, try to update your user externalids as an array first:

User.update({ _id: req.user._id }, { $set : { externalids: [] }}

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