Cast plain object to mongoose document

Posting my own answer so this doesn’t stay open: Version 4 models (stable released on 2015-03-25) now exposes a hydrate() method. None of the fields will be marked as dirty initially, meaning a call to save() will do nothing until a field is mutated. https://github.com/LearnBoost/mongoose/blob/41ea6010c4a84716aec7a5798c7c35ef21aa294f/lib/model.js#L1639-1657 It is very important to note that this is intended … Read more

Mongoose sort the aggregated result

The results returned from the aggregation pipeline are just plain objects. So you do the sorting as a pipeline stage, not as a separate operation: Recommend.aggregate( [ // Grouping pipeline { “$group”: { “_id”: ‘$roomId’, “recommendCount”: { “$sum”: 1 } }}, // Sorting pipeline { “$sort”: { “recommendCount”: -1 } }, // Optionally limit results … Read more

MongoError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string

As suggested in accepted answer, you need to have your local server to be run as a replica set to be able to perform transactions, as opposed to standalone server. However, in addition to the proposed solution, you can easily convert your Standalone local db to a Replica Set without using any third-party tool, by … Read more

find by _id with Mongoose

Because this query finds the doc in the shell: db.getCollection(‘stories’).find({_id:’572f16439c0d3ffe0bc084a4′}) That means that the type of _id in the document is actually a string, not an ObjectId like Mongoose is expecting. To find that doc using Mongoose, you’d have to define _id in the schema for Story as: _id: { type: String }

Named export ‘Types’ not found. The requested module ‘mongoose’ is a CommonJS module, which may not support all module.exports as named exports

TL;DR All you have to do is remove the curly braces from the Types. That should work. Just like this: import Types from ‘mongoose’ But the name does not matter. Explanation import Types from ‘mongoose’ works because we are importing the package’s default export (this is why the name we use does not matter). However, … Read more

Node.js – Mongoose – Check if a collection exists

Option 2 is probably the cleanest. Assuming you have a Mongoose Connection object named conn that’s been opened using mongoose.createConnection, you can access the native mongo Db object via conn.db. From there you can call collectionNames which should provide what you’re looking for: conn.db.collectionNames(function (err, names) { // names contains an array of objects that … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)