我正在学习使用mongodb,并尝试在一个更新查询中执行多项操作时,我收到$ addToSet错误。

码:

var insertBook = function(db, title, author, price, edition, img, tags, pages, user, callback) {
    db.collection('books').update(
        { $and:[{ "title":title }, { "edition":edition }] },
        {
            "title": title,
            "author":author,
            {$addToSet: { "img": { $each: img }}},  //error(1)
            {$addToSet: { "tags": { $each: tags }}}, //error(2)
            "edition": edition,
            "pages":pages,
            "price":price,
            "shared":{ $subtract: ["$shared", 0] },
            $inc: {"copies": 1},
            "availableCopies":{ $subtract: ["$copies","$shared"] },
            {$addToSet: { "ownedBy": user }}, //error(3)
            "registeredOn": { $type: "timestamp"}
        },
        { upsert: true }

    , function(err, result) {
        assert.equal(err, null);
        console.log("Inserted a document into the Books collection.");
        callback(result);
    });
};

MongoClient.connect(url, function(err, db) {
    assert.equal(err, null);
    var title = "Harry Potter and the chamber of secrets";
    var author = "J.K. Rowling";
    var price = 50.00;
    var img = "null";
    var tags = ["Fiction", "Magic"];
    var pages = 450;
    var user = "Amresh Venugopal";
    insertBook(db, title, author, price, edition, img, tags, pages, user, function(){
        db.close();
    });
});


错误:

/home/codewingx/repo/nodeapps/RESTful/model/bookPut.js:33
        {$addToSet: { "img": { $each: img }}},
        ^

SyntaxError: Unexpected token {


好像在$ addToSet的使用中我错过了一些东西。 https://docs.mongodb.org/manual/reference/operator/update/addToSet/#addtoset-modifiers处的示例仅使用$ addToSet操作。

是什么导致此错误?

最佳答案

您的更新语句包含更新整个文档,特定字段和汇总操作($ substract)的混合。您不能在更新台词中使用聚合运算符。如果没有这些聚合运算符,则可以使用如下所示的update语句。

您也不需要$ and,因为默认为and操作。


  db.collection('books').update(
  { "title":title, "edition":edition },
  {
    $set: {"title": title,
           "author": author,
           "edition": edition,
           "pages":pages,
           "price":price,
           "registeredOn": new Date()
          },
    $addToSet: { "img": { $each: img },
                "tags": { $each: tags },
                "ownedBy": user
               },

    $inc: {"copies": 1}
  },
  {upsert: true},
  function (err, res) {

  });

关于javascript - 更新mongodb时执行多个操作:$ addToSet,$ inc和聚合:$ subtract,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34693608/

10-09 14:10