As I delve into learning how to use mongodb, I encountered a challenge when attempting to execute multiple operations in a single update query. Specifically, I encountered an error related to the $addToSet method.
Code:
function insertBook(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();
});
});
Error:
/home/codewingx/repo/nodeapps/RESTful/model/bookPut.js:33
{$addToSet: { "img": { $each: img }}},
^
SyntaxError: Unexpected token {
It appears that I may have overlooked something in my usage of the $addToSet method. The guide on https://docs.mongodb.org/manual/reference/operator/update/addToSet/#addtoset-modifiers only demonstrates the $addToSet operation, so what could be causing this particular error?