These are chat archives for Automattic/mongoose

16th
May 2016
Michael
@me-12
May 16 2016 11:28
Can someone tell me whats wrong with this?
var game_schema = {
    last_modified: {
        whatever : String
    },
    // few more fields
};
whenever i am trying to update something i get the following error: [CastError: Cast to Object failed for value "{}" at path "last_modified"]
Harry Reeder
@hreeder
May 16 2016 15:18

Hey folks, I'm relatively new to mongoose and node in general, having inherited an application from my predecessor. I have an array of IDs of Objects contained in mongo, and I want to map that to an array of one of those object's properties, however in my mind I think my flow should be as follows:

["id1", "id2"].map(function(id){
  MongoObject.findOne({_id: id}, function(err, item) {
    return item.property;
  });
});

Obviously I can't do the above because the return doesn't execute in the outer scope. Can anyone suggest how my control flow should maybe look?

LeonineKing1199
@LeonineKing1199
May 16 2016 15:57
Ooh, you can use Promise.all.
Promise
  .all(arrayOfIds.map((id) => { return promiseReturningMongoQuery(id)}))
  .then(functionThatWillProcessMyArrayOfDocuments);
I like Mongo/Mongoose because dealing with databases sucks. Look at those 1,000 line SQL queries. Mongoose is great because you can do everything at the application level instead.
Harry Reeder
@hreeder
May 16 2016 15:58
Yeah, I've always tended to use an ORM no matter what language / database I use
LeonineKing1199
@LeonineKing1199
May 16 2016 16:00

There are actually probably multiple ways of doing what you want but basically, I'd suggest using Promises.

At our company, we kind of "cheat" and will use the standard Promise implementation in Mongoose by doing,

const mongoose = require('mongoose);
mongoose.Promise = global.Promise;
Mongoose's implementation of Promises doesn't support catch, I think so it's kind of meh to use.
Paul "Joey" Clark
@joeytwiddle
May 16 2016 16:02
I think that's fine because the next major release on mongoose will use ES6 promises by default. (y)
LeonineKing1199
@LeonineKing1199
May 16 2016 16:03
I'm very excited about that too! But just like async/await, I'm not holding my breath...
paulgrove
@paulgrove
May 16 2016 19:50
Hi! During pre('validation' is it possible to get the object before and after the changes? (without causing potential race conditions)