1

I am trying to update a value in a collection. The user clicks a button, and a number corresponding to that button, gets sent to the server to be added to the collection.

I cannot get the collection to update, but it works fine in the console if i use db.orders.update()

orders model:

// DB Initiation stuff

var orderSchema = new mongoose.Schema({ 
    status: String,
    rated: Number
});

var collection = 'orders';
var Order = db.model('Order', orderSchema, collection);

module.exports = Order;

client side (when button click)

// starID = 5; id = 50e6a57808a1d92dcd000001
socket.emit('rated', {rated: starID, id: id});

socket.js:

var Order = require('../models/orders');

socket.on('rated', function(data) { 
  /* Probably a better way to do this but, wrap
   * the id in 'ObjectId(id)'
   */
  var id = 'ObjectId("'+data.id+'")';
  Order.update( {_id: id}, {$set: {rated: data.rated}} );
   socket.emit('updated', {
     note: 'Some HTML notification to append'
   });  
});
1
  • Try using var id=ObjectId.fromString(data.id); instead of creating a string (where ObjectId = mongoose.Types.ObjectId). Commented Jan 4, 2013 at 13:47

3 Answers 3

1

Let Mongoose do the casting of the id string to an ObjectId:

socket.on('rated', function(data) { 
  Order.update( {_id: data.id}, {$set: {rated: data.rated}} );
   socket.emit('updated', {
     note: 'Some HTML notification to append'
   });  
});
Sign up to request clarification or add additional context in comments.

Comments

0

Mongoose expects a String as id. So passing an ObjectId does not work. Try:

Order.update( {_id: id.toString()}, ....... );

It is safe to use toString with both String and ObjectId.

Comments

0

I tried everything stated and it just didn't seem to work, so I changed the update code to:

Order.findOne({_id : id}, function(err, doc) {
  doc.rated = data.rated;
  doc.status = data.status;
  doc.save();
});

And now it works fine. Thank you to everyone who contributed to answering

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.