使用批量写入在Mongo DB文档中的数组内插入值

时间:2018-04-21 09:57:29

标签: javascript arrays node.js mongodb mongoose

我有一个我想要更新数组的集合。架构如下: -

var testSchema = new mongoose.Schema({
...,
comments : {
    type : [ String ],
    required: true
},
...
});

我收集文档的所有ID,然后尝试为必要的ID插入通用注释。 id_array和comment正在通过post请求正确传递,并且正在控制台日志中记录。我使用的代码如下: -

console.log(id_array);
console.log(comment);
var bulk = testSchema.collection.initializeOrderedBulkOp();
bulk.find({_id: {$in: id_array}}).update({$push: {comments: comment}});
bulk.execute(function (error, doc) {
var response = {
  status : 200,
  message : doc
};
if (error) {
  console.log('Error');
  response.status = 500;
  response.message = err;
} else if (!doc) {
  console.log(doc);
  response.status = 404;
  response.message = {
    "message" : "Callback failed"
   };
 }
 console.log(doc);
 res
 .status(response.status)
 .json(response.message);
});

执行此代码段后,我们得到: -

BulkWriteResult {
ok: [Getter],
nInserted: [Getter],
nUpserted: [Getter],
nMatched: [Getter],
nModified: [Getter],
nRemoved: [Getter],
getInsertedIds: [Function],
getUpsertedIds: [Function],
getUpsertedIdAt: [Function],
getRawResponse: [Function],
hasWriteErrors: [Function],
getWriteErrorCount: [Function],
getWriteErrorAt: [Function],
getWriteErrors: [Function],
getLastOp: [Function],
getWriteConcernError: [Function],
toJSON: [Function],
toString: [Function],
isOk: [Function] }

但是注释字段未更新。我哪里错了?

0 个答案:

没有答案