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'
});
});
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'
});
});
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.
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