4

I have a website written with Meteor and external nodejs server that works with meteor's mongo. I create new documents in collection tradeOffers on Meteor side and poll for new documents in this collection on external server (I use mongoose). Everything works fine except that mongoose returns documents without the '_id' property. My code is something like this:

// Meteor
var TradeOffers = new Mongo.Collection('tradeOffers');
TradeOffers.insert({ ... });

// Mongoose
var tradeOfferSchema = new mongoose.Schema({ ... }, { collection: 'tradeOffers' });
var TradeOffer = mongoose.model('TradeOffer', tradeOfferSchema);
TradeOffer.find({}).exec(function(err, results) {
  results.forEach(function(tradeOffer) {
    console.log(tradeOffer._id); // undefined
  });
});

I noticed that documents created in Meteor have '_id' field of type 'String' and documents created with mongoose have '_id' of type 'ObjectId'. But even if that's the problem, how do I solve it? I could not find any information. Thank you in advance.

starky
  • 640
  • 5
  • 13
  • You answered it yourself `_id` is an `ObjectId` wich can't be logged like this you would need to parse it to as a String `console.log(tradeOffer._id.toString());`. Also see [this question](http://stackoverflow.com/questions/13104690/nodejs-mongodb-object-id-to-string) – Philipp Beck May 13 '16 at 10:55
  • @DerTieran already tried that. It says `'Cannot read property 'toString' of undefined'.` – starky May 13 '16 at 10:58
  • @DerTieran if you see from a `console.log`, the thing you're trying to log either has its `toString` to return `"undefined"` or it is the said string, or it is really is `undefined` (the most likely result). – Patrick J. S. May 13 '16 at 11:02
  • @starky have you tried to log the whole Object so `console.log(tradeOffer)` so you can see if `_id` is defined? – Philipp Beck May 13 '16 at 11:06
  • Have you tried to `log` the whole object? How does your schema look like? Do you have one of the `_id` and `id` options set? Can you verify that the objects have an Id in the database (e.g. with the `mongo` client). – Patrick J. S. May 13 '16 at 11:06
  • @DerTieran It's not defined. – starky May 13 '16 at 11:34
  • @PatrickJ.S. Yes, I did try log the whole object and there was no '_id' or 'id' properties. But using mongo client I can see there is '_id' field and it's a string. – starky May 13 '16 at 11:35

1 Answers1

4

Solved by adding _id: String, to schema definition.

starky
  • 640
  • 5
  • 13