我将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,而不是重置它。
答案 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}
)
}