我正在学习使用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操作。
可能导致此错误的原因是什么?
答案 0 :(得分:3)
您的更新语句混合了更新整个文档,特定字段和聚合操作($ substract)。您不能在更新staments中使用聚合运算符。如果没有这些聚合运算符,您可以使用如下的update语句。
您也不需要$和,默认为和操作。
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) {
});