How do you turn a Mongoose document into a plain object?

I have a document from a mongoose find that I want to extend before JSON encoding and sending out as a response. If I try adding properties to the doc it is ignored. The properties don’t appear in Object.getOwnPropertyNames(doc) making a normal extend not possible. The strange thing is that JSON.parse(JSON.encode(doc)) works and returns an … Read more

Comparing mongoose _id and strings

I have a node.js application that pulls some data and sticks it into an object, like this: var results = new Object(); User.findOne(query, function(err, u) { results.userId = u._id; } When I do an if/then based on that stored ID, the comparison is never true: if (results.userId == AnotherMongoDocument._id) { console.log(‘This is never true’); } … Read more

Avoid “current URL string parser is deprecated” warning by setting useNewUrlParser to true

I have a database wrapper class that establishes a connection to some MongoDB instance: async connect(connectionString: string): Promise<void> { this.client = await MongoClient.connect(connectionString) this.db = this.client.db() } This gave me a warning: (node:4833) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option … Read more

Push items into mongo array via mongoose

Basically I have a mongodb collection called ‘people’ whose schema is as follows: people: { name: String, friends: [{firstName: String, lastName: String}] } Now, I have a very basic express application that connects to the database and successfully creates ‘people’ with an empty friends array. In a secondary place in the application, a form is … Read more

Stop Mongoose from creating _id property for sub-document array items

If you have subdocument arrays, Mongoose automatically creates ids for each one. Example: { _id: “mainId” subDocArray: [ { _id: “unwantedId”, field: “value” }, { _id: “unwantedId”, field: “value” } ] } Is there a way to tell Mongoose to not create ids for objects within an array? 7 Answers 7