Posts

Showing posts with the label Mongoose

Bulk Upsert In MongoDB Using Mongoose

Answer : Not in "mongoose" specifically, or at least not yet as of writing. The MongoDB shell as of the 2.6 release actually uses the "Bulk operations API" "under the hood" as it were for all of the general helper methods. In it's implementation, it tries to do this first, and if an older version server is detected then there is a "fallback" to the legacy implementation. All of the mongoose methods "currently" use the "legacy" implementation or the write concern response and the basic legacy methods. But there is a .collection accessor from any given mongoose model that essentially accesses the "collection object" from the underlying "node native driver" on which mongoose is implemented itself: var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var sampleSchema = new Schema({},{ "strict": false }); va...

Converting A Mongo Stored Date Back Into Milliseconds Since Unix Epoch When Loaded?

Answer : You can add the numerical milliseconds version of timestamp as a virtual attribute on the schema: schema.virtual('timestamp_ms').get(function() { return this.timestamp.getTime(); }); Then you can enable the virtual field's inclusion in toObject calls on model instances via an option on your schema: var schema = new Schema({ timestamp: Date }, { toObject: { getters: true } }); var schema = new Schema({ timestamp: {type:Number, default: new Date().getTime()} }); Hope this will solve your issue. As a best practice, I would say: keep your data the type it deserves . Anyway, if your client needs to treat with numbers, you can simply pass the date as milliseconds to the client, and still work with Date objects in Node. Just call timestamp.getTime() and ta-da, you have your unix timestamp ready for the client.

Convert Mongoose Docs To Json

Answer : You may also try mongoosejs's lean() : UserModel.find().lean().exec(function (err, users) { return res.end(JSON.stringify(users)); } Late answer but you can also try this when defining your schema. /** * toJSON implementation */ schema.options.toJSON = { transform: function(doc, ret, options) { ret.id = ret._id; delete ret._id; delete ret.__v; return ret; } }; Note that ret is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters. And then: Model .findById(modelId) .exec(function (dbErr, modelDoc){ if(dbErr) return handleErr(dbErr); return res.send(modelDoc.toJSON(), 200); }); Edit: Feb 2015 Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example. OP: UserModel .find({}) // will get all...