简体   繁体   中英

Mongoose/Mongo Unique subdocuments

Hey guys I'm having trouble finding an answer to my problem. I'd like to have my database save subscriptions which saves separate hashtags. I'd like each subscription to have unique hashtags but using unique for my schema on the hashtag name doesn't work. Within each hashtag I have services for that tag(unrelated to my issue here). Here's my Schema...

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

var Services = new Schema ({ 
    type : {type : String},
    subscriptionInfo : Schema.Types.Mixed,
    data : Schema.Types.Mixed
});

var Hashtags = new Schema ({
    name: {type : String},
    services : [Services]
});

var SubscriptionSchema = new Schema ({
    eventId : {type : Number, unique : true},
    hashtags : [Hashtags]
});

module.exports = mongoose.model('Subscription', SubscriptionSchema);

Initially I create a subscription, which creates the entry with an empty hashtag object. I'd like to periodically add hashtags but I want them to be unique. I'm not sure how to do this.

You want to use the $addToSet operator to add Hashtag s to the hashtags array. There's multiple ways to do this in Mongoose. For example, you could use MongooseArray#addToSet , as shown below where I've simplified things a bit by substituting a String for a complete Hashtag object:

var Subscription = mongoose.model("Subscription", SubscriptionSchema);
var subscription = new Subscription({eventId: 11, hashtags: ["#monkeys"]});
subscription.save(callback); // subscription will be saved to database with hashtags = ["#monkeys"]

// later...
subscription.hashtags.addToSet("#monkeys", "#trampolines");
subscription.save(callback); // subscription now has hashtags = ["#monkeys", "#trampolines"]

You can also use the Model.update function:

Subscription.update({ eventId: id }, { hashtags: { $addToSet: "#trampolines" }}, callback);

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