简体   繁体   中英

Using Node.js to add Object in a MongoDB Array

I have a great problem with a school project:

I created a site that uses MongoDB as DataBase and Node.js as Server, in the server I have a method to add products to a cart, the object that i'm trying to add to the cart array is this:

{"cart" : {"idproduct" : idproduct, "collectionproduct" : 'comicbooks'}}

And the code I'm using to add the object to the array is this:

db.collection("users").update({"_id": new ObjectId(userid)}, {$push: {"cart" : {"idproduct" : new ObjectId(idproduct), "collectionproduct" : 'comicbooks'}}}, { "$upsert": true });

The real strange thing is that I've tried it on mongo itself, and it worked, but when I try to run the node code then it doesn't, but it doesn't even give me an error.

I even tried the same thing with $addToSet and again, with node doesn't work but it doesn't give me any error, but in mongo it works.

If anyone knows what is the problem then please, please help me, as quick as you can.

If you are using mongodb-native , then try this

var insertDocuments = function(db, callback) {
  var collection = db.collection('users');
  collection.insert([
    "cart" : {"idproduct" : idproduct, "collectionproduct" : 'comicbooks'}}
  ], function(err, result) {
    callback(result);
  });
}

and call the function using

insertDocuments(db, function() {
  db.close();
});

Is this answer your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM