在没有 ObjectId 的情况下通过猫鼬更新条目

Updating an entry through mongoose without ObjectId

我有一个 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 添加到事件中。当然,这个事件已经存在于数据库中。

function addUserToEvent(user_id, event_id) {

}

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

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

这是将元素附加到现有文档中的数组的方式:

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*/

针对您的具体情况:

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