aitchkhan
aitchkhan

Reputation: 1952

Mongodb find and insertMany only if the matched combination does not returns to truthy

I have to insert a batch in action collection which looks like this:

[

  {

    "userId": "57ee65fef5a0c032877725db",

    "postId": "57f63ce196b01748e4712ed3",

    "type": "like"

  },

  {

    "userId": "57ee65fef5a0c032877725db",

    "postId": "57f7335223a76c0f780a44c5",

    "type": "dismiss"

  },

  {

    "userId": "57ee65fef5a0c032877725db",

    "postId": "57f7335223a76c0f780a44c5",

    "type": "dislike"

  }

]

Schema of actions collections looks like:

const ActionSchema = new mongoose.Schema({
    userId: mongoose.Schema.Types.ObjectId,
    postId: mongoose.Schema.Types.ObjectId,
    type: String
}, {
    timestamps: true
});

but before inserting I want to make sure that this specific "userId" and "postId" within this array has no matched combination in the action collection of db. Since a user can only perform a single action given a particular post, posted by other users.

Upvotes: 1

Views: 388

Answers (3)

muhammad abdulmoiz
muhammad abdulmoiz

Reputation: 44

Haroon your question was not self explanatory but what I understand from your scenario is you need a unique set of postId AND userId so i think you need a compound index to be form like. Let me know if get the scenario wrong

anySchema.index({field1: 1, field2: 1}, {unique: true});

For your case it will be

ActionSchema.index({postId: 1, userId: 1}, {unique: true});

It will assure that you will always have a unique set of postId and userId

Upvotes: 0

Aishwarya Singh
Aishwarya Singh

Reputation: 11

'use strict';
var mongoose = require('mongoose');

var accountTypeSchema = new mongoose.Schema({
    name:{type:String, index: { unique: true }},
    created: {type: Date, default: Date.now()},
    deleted: {type: Number, default: 0}
});

module.exports = mongoose.model('AccountType', accountTypeSchema);

Upvotes: 1

Aishwarya Singh
Aishwarya Singh

Reputation: 11

You mean to have set of unique postId, userId in the given JSON, no postId, userId should repeat ?

Upvotes: 0

Related Questions