简体   繁体   English

Mongodb / Mongoose:填充ObjectIds数组(引用)

[英]Mongodb/Mongoose: Filling Array of ObjectIds (references)

I have a mongodb running (MEAN environment) with two collections (users and books). 我正在运行一个mongodb(在MEAN环境中),其中包含两个集合(用户和书籍)。 One of those collections (myusers) contains an array of Objectids (references to documents of books collection) as such: 这些集合之一(myusers)包含一个Objectid数组(对书籍集合文档的引用),如下所示:

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. 在运行时,我想不断用新书文档的ID填充该数组(外部ID)。 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. 尝试使用$ addToSet而不是$ push来避免重复的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. 您可能遇到的问题是您以前使用$set来更新用户。 This will initially create externalids as string, not array, hence you cannot use $push/$addToSet on externalids afterwards. 这将最初将externalids创建为字符串,而不是数组,因此您之后不能在$push/$addToSet上使用$push/$addToSet To correct that, try to update your user externalids as an array first: 若要更正此问题,请尝试首先将您的用户externalid更新为数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM