All Questions
50,528
questions
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 ...
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?
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},
...
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 },
...
362
votes
13
answers
158k
views
How do I manage MongoDB connections in a Node.js web application?
I'm using the node-mongodb-native driver with MongoDB to write a website.
I have some questions about how to manage connections:
Is it enough using only one MongoDB connection for all requests? Are ...
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' : [
'...
349
votes
24
answers
574k
views
How do I remove documents using Node.js Mongoose?
FBFriendModel.find({
id: 333
}, function (err, docs) {
docs.remove(); //Remove all the documents that match!
});
The above doesn't seem to work. The records are still there.
Can someone fix?...
337
votes
4
answers
336k
views
How to search in array of object in mongodb
Suppose the mongodb document(table) 'users' is
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
...
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"
},
...
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 ...
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.
321
votes
33
answers
548k
views
Render basic HTML view?
I have a basic Node.js app that I am trying to get off the ground using the Express framework. I have a views folder where I have an index.html file. But I receive the following error when loading the ...
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 ...
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(...
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 ...
257
votes
12
answers
358k
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 ...
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 ...
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()....
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!
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 ...
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('...
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(...
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": ...
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",
...
197
votes
25
answers
112k
views
How to properly reuse connection to Mongodb across NodeJs application and modules
I've been reading and reading and still am confused on what is the best way to share the same database (MongoDb) connection across whole NodeJs app. As I understand connection should be open when app ...
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 ...
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 ...
184
votes
10
answers
376k
views
How to sort a collection by date in MongoDB?
I am using MongoDB with Node.JS. I have a collection which contains a date and other rows. The date is a JavaScript Date object.
How can I sort this collection by date?
181
votes
47
answers
645k
views
MongoError: connect ECONNREFUSED 127.0.0.1:27017
I'm using NodeJS wih MongoDB using mongodb package. When I run mongod command it works fine and gives "waiting for connection on port 27017". So, mongod seems to be working. But MongoClient ...
176
votes
6
answers
243k
views
How to Create and Use Enum in Mongoose [closed]
I am trying to create and use an enum type in Mongoose. I checked it out, but I'm not getting the proper result. I'm using enum in my program as follows:
My schema is:
var RequirementSchema = new ...
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, ...
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.
...
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 ...
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 ...
166
votes
13
answers
205k
views
db.collection is not a function when using MongoClient v3.0
I have been trying W3schools tutorial on nodeJS with MongoDB.
When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:
...
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: [
...
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,
...
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, ...
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'
...
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, ...
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....
159
votes
36
answers
142k
views
Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version
I am getting the below error:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Here are my ...
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 ...
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" ...
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 ...
149
votes
23
answers
157k
views
Can I determine if a string is a MongoDB ObjectID?
I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?
Here is the coffeescript ...
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 ...
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: ...
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:
...
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 ...