通过mongoose更新条目而不使用ObjectId

时间:2017-04-24 17:10:33

标签: node.js mongodb mongoose mongoose-schema

我将Mongoose架构定义为

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    user_id: String,
    event_organizer: [String],
});

module.exports = mongoose.model('User',userSchema);

现在,我有一个功能,我希望将此用户的ID添加到事件中。当然,这个事件已经存在于DB中。

function addUserToEvent(user_id, event_id) {

}

如何在架构中定义的用户的event_id数组中添加event_organizer

可能已经填充了数组,我需要附加id,而不是重置它。

1 个答案:

答案 0 :(得分:1)

This is how you append an element to an array in an existing document:

Document.update(
     {_id:existing_document_id}, 
     {$push: {array: element}}, 
     {upsert: true}
) /*upsert true if you want mongoose to create the document in case it does not exist*/

For your specific case:

function addUserToEvent(user_id, event_id) {
    User.update(
                {_id:user_id}, 
                {$push: {event_organizer: event_id}}, 
                {upsert: true}
    )
}