Mongodb只有在匹配的组合不返回真的时候才能find并插入

我必须在行动集合中插入一个批处理,如下所示:

[ { "userId": "57ee65fef5a0c032877725db", "postId": "57f63ce196b01748e4712ed3", "type": "like" }, { "userId": "57ee65fef5a0c032877725db", "postId": "57f7335223a76c0f780a44c5", "type": "dismiss" }, { "userId": "57ee65fef5a0c032877725db", "postId": "57f7335223a76c0f780a44c5", "type": "dislike" } ] 

操作集合的模式如下所示:

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

但在插入之前,我想确保这个数组中的这个特定的“userId”和“postId”在db的action collection中没有匹配的组合。 由于用户只能执行由其他用户发布的特定post的单个操作。

哈龙你的问题是不是自我解释,但是我从你的情况了解是你需要一套独特的postId userId,所以我认为你需要一个复合索引forms。 让我知道如果得到错误的情况

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

对于你的情况将是

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

这将确保您将始终拥有一套独特的postId和userId

 '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); 

你的意思是在给定的JSON中设置唯一的postId,userId,否postId,userId应该重复?