Questions tagged [mongoose]

Mongoose is a MongoDB object modeling tool, or ODM (Object Document Mapper), written in JavaScript and designed to work in an asynchronous environment.

Filter by
Sorted by
Tagged with
774 votes
13 answers
679k views

Find MongoDB records where array field is not empty

All of my records have a field called "pictures". This field is an array of strings. I now want the newest 10 records where this array IS NOT empty. I've googled around, but strangely enough I haven'...
Jelle De Loecker's user avatar
716 votes
14 answers
836k views

Find document with array that contains a specific value

If I have this schema... person = { name : String, favoriteFoods : Array } ... where the favoriteFoods array is populated with strings. How can I find all persons that have "sushi" as their ...
Ludwig Magnusson's user avatar
509 votes
23 answers
714k views

How do I update/upsert a document in Mongoose?

Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :) Here's the deal: I have a contact schema and ...
Traveling Tech Guy's user avatar
436 votes
9 answers
253k views

What is the "__v" field in Mongoose

I'm using Mongoose version 3 with MongoDB version 2.2. I've noticed a __v field has started appearing in my MongoDB documents. Is it something to do with versioning? How is it used?
Simon Lomax's user avatar
  • 8,862
431 votes
17 answers
464k views

Mongoose: findOneAndUpdate doesn't return updated document

Below is my code var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var Cat = mongoose.model('Cat', { name: String, age: {type: Number, default: 20}, ...
Dreams's user avatar
  • 8,438
367 votes
24 answers
595k views

E11000 duplicate key error index in mongodb mongoose

Following is my user schema in user.js model - var userSchema = new mongoose.Schema({ local: { name: { type: String }, email : { type: String, require: true, unique: true }, ...
Trialcoder's user avatar
  • 5,926
361 votes
9 answers
333k views

mongodb/mongoose findMany - find all documents with IDs listed in array

I have an array of _ids and I want to get all docs accordingly, what's the best way to do it ? Something like ... // doesn't work ... of course ... model.find({ '_id' : [ '...
ezmilhouse's user avatar
  • 9,053
331 votes
8 answers
141k views

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" }, ...
Atlas's user avatar
  • 3,413
331 votes
12 answers
493k views

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 ...
Neurax's user avatar
  • 3,717
327 votes
36 answers
386k views

How to paginate with Mongoose in Node.js?

I am writing a webapp with Node.js and mongoose. How can I paginate the results I get from a .find() call? I would like a functionality comparable to "LIMIT 50,100" in SQL.
Thomas's user avatar
  • 10.5k
310 votes
10 answers
196k views

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 ...
pat's user avatar
  • 3,563
286 votes
9 answers
217k views

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 ...
respectTheCode's user avatar
281 votes
22 answers
346k views

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(...
Lion's user avatar
  • 17.3k
261 votes
11 answers
182k views

Difference between MongoDB and Mongoose

I wanted to use the mongodb database, but I noticed that there are two different databases with either their own website and installation methods: mongodb and mongoose. So I came up asking myself this ...
Ravindra Galav's user avatar
257 votes
12 answers
359k views

Node.js Mongoose.js string to ObjectId function

Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a ...
JRPete's user avatar
  • 3,144
255 votes
22 answers
277k views

add created_at and updated_at fields to mongoose schemas

Is there a way to add created_at and updated_at fields to a mongoose schema, without having to pass them in everytime new MyModel() is called? The created_at field would be a date and only added when ...
chovy's user avatar
  • 74.2k
243 votes
21 answers
479k views

How to sort in mongoose?

I find no documentation for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12 writer.limit(5).sort(['test', 1]).group('name') But it doesn't work for me: Post.find()....
Philippe Rathé's user avatar
219 votes
11 answers
256k views

In Mongoose, how do I sort by date? (node.js)

let's say I run this query in Mongoose: Room.find({}, (err,docs) => { }).sort({date:-1}); This doesn't work!
TIMEX's user avatar
  • 266k
217 votes
7 answers
225k views

How can I generate an ObjectId with mongoose?

I'd like to generate a MongoDB ObjectId with Mongoose. Is there a way to access the ObjectId constructor from Mongoose? This question is about generating a new ObjectId from scratch. The generated ID ...
Dmitry Minkovsky's user avatar
211 votes
51 answers
237k views

Cannot overwrite model once compiled Mongoose

Not Sure what I'm doing wrong, here is my check.js var db = mongoose.createConnection('localhost', 'event-db'); db.on('error', console.error.bind(console, 'connection error:')); var a1= db.once('...
Anathema.Imbued's user avatar
207 votes
32 answers
412k views

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

When sending a request to /customers/41224d776a326fb40f000001 and a document with _id 41224d776a326fb40f000001 does not exist, doc is null and I'm returning a 404: Controller.prototype.show = ...
gremo's user avatar
  • 47.9k
205 votes
8 answers
366k views

Mongoose, Select a specific field with find

I'm trying to select only a specific field with exports.someValue = function(req, res, next) { //query with mongoose var query = dbSchemas.SomeValue.find({}).select('name'); query.exec(...
TlonXP's user avatar
  • 3,415
204 votes
11 answers
327k views

MongoDB/Mongoose querying at a specific date?

Is it possible to query for a specific date ? I found in the mongo Cookbook that we can do it for a range Querying for a Date Range Like that : db.posts.find({"created_on": {"$gte": start, "$lt": ...
Unitech's user avatar
  • 5,891
199 votes
16 answers
184k views

Populate nested array in mongoose

How can I populate "components" in the example document: { "__v": 1, "_id": "5252875356f64d6d28000001", "pages": [ { "__v": 1, "_id": "5252875a56f64d6d28000002", ...
Anton Shuvalov's user avatar
195 votes
10 answers
198k views

Properly close mongoose's connection once you're done

I'm using mongoose in a script that is not meant to run continuously, and I'm facing what seems to be a very simple issue yet I can't find an answer; simply put once I make a call to any mongoose ...
Lepidosteus's user avatar
193 votes
8 answers
168k views

Mongoose - What does the exec function do?

I came across a piece of Mongoose code that included a query findOne and then an exec() function. Ive never seen that method in Javascript before? What does it do exactly?
user439133's user avatar
  • 2,053
186 votes
35 answers
186k views

Failed to load c++ bson extension

A total node noob here. I've been trying to set up a sample node app but the following error keeps popping up every time I try to run: node app Failed to load c++ bson extension, using pure JS ...
Theja's user avatar
  • 2,448
186 votes
8 answers
176k views

Mongoose and multiple database in single node.js project

I'm doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the problem is Mongoose doesn't ...
pupot's user avatar
  • 1,901
176 votes
6 answers
430k views

How to define object in array in Mongoose schema correctly with 2d geo index

I'm currently having problems in creating a schema for the document below. The response from the server always returns the "trk" field values as [Object]. Somehow I have no idea how this should work, ...
niels_h's user avatar
  • 1,959
176 votes
18 answers
169k views

mongoError: Topology was destroyed

I have a REST service built in node.js with Restify and Mongoose and a mongoDB with a collection with about 30.000 regular sized documents. I have my node service running through pmx and pm2. ...
dreagan's user avatar
  • 2,436
173 votes
11 answers
198k views

How to access a preexisting collection with Mongoose?

I have a large collection of 300 question objects in a database test. I can interact with this collection easily through MongoDB's interactive shell; however, when I try to get the collection through ...
theabraham's user avatar
  • 16.1k
173 votes
8 answers
66k views

Why does mongoose always add an s to the end of my collection name

For example, this code results in a collection called "datas" being created var Dataset = mongoose.model('data', dataSchema); And this code results in a collection called "users" being created var ...
Bob Ren's user avatar
  • 2,149
166 votes
4 answers
238k views

Mongoose's find method with $or condition does not work properly

Recently I start using MongoDB with Mongoose on Nodejs. When I use Model.find method with $or condition and _id field, Mongoose does not work properly. This does not work: User.find({ $or: [ ...
Younghan's user avatar
  • 4,947
164 votes
30 answers
205k views

Server Discovery And Monitoring engine is deprecated

I am using Mongoose with my Node.js app and this is my configuration: mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, ...
iLiA's user avatar
  • 3,103
162 votes
10 answers
140k views

Delete a key from a MongoDB document using Mongoose

I'm using the Mongoose Library for accessing MongoDB with node.js Is there a way to remove a key from a document? i.e. not just set the value to null, but remove it? User.findOne({}, function(err, ...
Daniel Beardsley's user avatar
162 votes
15 answers
250k views

Mongoose, update values in array of objects

Is there a way to update values in an object? { _id: 1, name: 'John Smith', items: [{ id: 1, name: 'item 1', value: 'one' },{ id: 2, name: 'item 2', value: 'two' ...
lostintranslation's user avatar
162 votes
4 answers
62k views

mongoDB/mongoose: unique if not null

I was wondering if there is way to force a unique collection entry but only if entry is not null. e Sample schema: var UsersSchema = new Schema({ name : {type: String, trim: true, index: true, ...
ezmilhouse's user avatar
  • 9,053
160 votes
9 answers
99k views

Mongoose -- Force collection name

I am trying to use mongoose to create a database and a collection in it. My code is: var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost/testdb'); var Schema = mongoose....
ravi's user avatar
  • 1,609
158 votes
6 answers
129k views

Mongoose subdocuments vs nested schema

I'm curious as to the pros and cons of using subdocuments vs a deeper layer in my main schema: var subDoc = new Schema({ name: String }); var mainDoc = new Schema({ names: [subDoc] }); or var ...
cyberwombat's user avatar
  • 39.1k
154 votes
8 answers
107k views

How do you use Mongoose without defining a schema?

In previous versions of Mongoose (for node.js) there was an option to use it without defining a schema var collection = mongoose.noSchema(db, "User"); But in the current version the "noSchema" ...
Christopher Tarquini's user avatar
153 votes
9 answers
303k views

How to get all count of mongoose model?

How can I know the count of a model that data has been saved? there is a method of Model.count(), but it doesn't seem to work. var db = mongoose.connect('mongodb://localhost/myApp'); var ...
smilexu's user avatar
  • 1,533
153 votes
5 answers
219k views

Referencing another schema in Mongoose

if I have two schemas like: var userSchema = new Schema({ twittername: String, twitterID: Number, displayName: String, profilePic: String, }); var User = mongoose.model('User') ...
s_curry_s's user avatar
  • 3,382
149 votes
2 answers
36k views

Mongoose indexing in production code

Per the Mongoose documentation for MongooseJS and MongoDB/Node.js : When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. While nice for ...
Nick S.'s user avatar
  • 2,213
146 votes
7 answers
167k views

How do I limit the number of returned items?

myModel.find({}, function(err, items) { console.log(items.length); // Big number }); How can I limit the returned items to only the latest 10 items that were inserted?
Running Turtle's user avatar
145 votes
6 answers
195k views

Mongoose query where value is not null

Looking to do the following query: Entrant .find enterDate : oneMonthAgo confirmed : true .where('pincode.length > 0') .exec (err,entrants)-> Am I doing the where ...
wesbos's user avatar
  • 26.1k
142 votes
3 answers
116k views

Mongoose findByIdAndUpdate not returning correct model

I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback. Here's the code: var id = args._id; var updateObj = {updatedDate: ...
JonRed's user avatar
  • 2,893
135 votes
37 answers
117k views

Mongoose Unique index not working!

I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this: ...
foobar's user avatar
  • 11.2k
133 votes
8 answers
151k views

Mongoose (mongodb) batch insert?

Does Mongoose v3.6+ support batch inserts now? I've searched for a few minutes but anything matching this query is a couple of years old and the answer was an unequivocal no. Edit: For future ...
Geuis's user avatar
  • 41.7k
131 votes
14 answers
141k views

Return certain fields with .populate() from Mongoose

I'm getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs and didn't find a proper ...
Sleep Deprived Bulbasaur's user avatar
130 votes
17 answers
295k views

ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

I'm facing this weird issue in NodeJS when using with Passport.js, Express and Mongoose. Basically, I get an error saying "Cannot set headers after they are sent to the client" even though I don't ...
lourdesr's user avatar
  • 1,411

1
2 3 4 5
937