【问题标题】:Unable to Insert Data into a collection无法将数据插入集合
【发布时间】:2016-08-22 05:52:21
【问题描述】:

我有官员模式,如果用户想要修复约会,他的条目会在数据库中进行。架构是:

officerSchema = mongoose.Schema({
    email : {type: String,
        index: { unique: true }
    },
    appointmentList : Array // array of jsonObject of dates and userID
});

AppointmentList 是一个 JSON 对象数组,其中包含必须与其进行约会的官员的 ID、日期和用户 ID(想要修复约会的用户)。

但是为了避免重复的约会条目,我一直在使用互联网上提到的几种方法。到目前为止,他们都没有为我工作过。我在下面发布代码。下面代码的问题是它永远不会在约会列表中插入任何数据。但是,如果我使用 save() 而不是 update() 会发生插入,但也会插入重复项。

这是我想从数据库中添加到数组中的 JSON 对象,

{
    "id": "1321231231",
    "appointment": {
        "userID": "31321",
        "date": "24 March"
    }
}

var ID = requestObject.id; 
var newObject =  {$addToSet: requestObject.appointment};
OfficerModel.findOne({_id : ID}, function(err, foundData) {
    if(err) {
        console.log(err);
        return;
    }
    else {
            var dbList = foundData.list;
            dbList.push(newObject);
            foundData.update(function(err, updatedData) {
                if(err) {
                    console.log( err);
                }
                else {
                    console.log("successful");
                }
            });
    }
});

【问题讨论】:

    标签: json node.js mongodb mongoose mean-stack


    【解决方案1】:

    使用$addToSet 运算符可能对您有用。

    var appt = {
      id: "1321231231",
      appointment: {
        userID: "31321",
        date: "24 March"
      }
    }
    
    Officer.update(
      {_id: ID}, 
      {$addToSet: {appointmentList: appt}},
      function(err) { ... }
    );
    

    但这不是一个完美的解决方案,因为 {one: 1, two: 2} 和​​ {two: 2, one: 1} 不被解释为相等,因此它们都可以通过 $addToSet 添加到数组中。

    为了完全避免重复,你可以这样做:

    var appt = {
      id: "1321231231",
      appointment: {
        userID: "31321",
        date: "24 March"
      }
    };
    
    Officer.findOne(
      {_id: ID, 'appointmentList.id': appt.id}, 
      function(err, officerDoc) {
        if (err) { ... }
    
        // since no document matched your query, add the appointment
        if (!officerDoc) {
          Officer.update(
            {_id: ID}, 
            {$push: {appointmentList: appt}}, 
            function(err) { ... }
          );
        }
    
        // since that appointment already exists, update it
        else {
          Officer.update(
            {_id: ID, 'appointmentList.id': appt.id},
            {$set: {'appointmentList.$.appointment': appt.appointment}},
            function(err) { ... }
          );
        }
      }
    );
    

    上面更新现有约会的操作使用positional operator

    【讨论】:

    • 几个问题:'appointmentList.id' 可以告诉 mongoose 查看名为约会列表的表/集合字段,然后遍历约会列表字段具有的所有 JsonObjects 并将它们与提供的 id 匹配,对吗?如果是这样,这意味着如果我们有类似的约会列表=[{a:1, [{b:7}]}, ...] 我们可以通过约会列表.a.b 检查“b”吗?如果不是,我们如何访问 b?有没有关于这个的教程?
    猜你喜欢
    • 1970-01-01
    • 2014-11-12
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多