【问题标题】:check if number exists in subdocument with Mongoose使用 Mongoose 检查子文档中是否存在数字
【发布时间】:2017-09-28 19:57:05
【问题描述】:

我有一个看起来像这样的文档:

var User = new Schema({
    _id: ObjectId,
    name: String,
    position: [{
              _id:ObjectId,
              index_number:Number,
                    preference:[{
                        candidate_id: String,
                        weightedScore:Number,
                        position_id:String,
                        candidate_index_number:Number
                    }],

当我添加一个位置时,我使用var index_number = Math.floor(100000 + Math.random() * 900000);生成一个index_number

但在添加之前,我需要检查该数字是否存在于子文档中的任何其他位置。所以我需要检查号码,如果号码确实存在,则再次运行该函数,直到我得到一个不存在的号码.. 但是这个函数并没有进入子文档..

 User.count({index_number: index_number}, function (err, count){
      if(count>0){
            console.log("no");
      }
      else{
          console.log("okay");
      }

如何循环遍历函数并检查子文档中的 index_number?还是有一种我不知道的方法可以让我插入一个不是 Mongoose 的对象 ID 的唯一数字?

【问题讨论】:

  • 你可以只允许在 index_number 字段中存储唯一的数字,如果你愿意,我可以告诉你怎么做?
  • @sacDahal 哦,是的,那太好了!

标签: node.js math random mongoose subdocument


【解决方案1】:

您可以更改字段 index_number 以仅存储唯一值。

index_number: {type: Number, index: { unique: true } },

因此,如果发生任何重复,它将在您的回调中抛出一个错误,您可以捕获该错误。

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 2015-11-27
    • 2019-12-12
    • 2019-03-04
    • 2023-03-07
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多