Mongoose JS findOne returning NULL - node.js

My code below is returning NULL immediately when it should return a document, seems to be specific to this collection as my other findOne's for different collections are working as expected.
function findData(rowObj) {
console.log(rowObj.field);
console.log(Mongoose.connection.readyState);
return DataImport.findOne({
ROW: rowObj.field
});
}
My collection has many fields, ideally I wouldn't use a schema as I am not updating or adding from this collection, just reading from it;
const mongoose = require('mongoose');
const { Schema } = mongoose;
const dataImportSchema = new Schema({});
const DataImport = mongoose.model(
'DataImport',
dataImportSchema,
'DataImport'
);
module.exports = DataImport;
I have however tried this with all of the document fields in the schema but get the same result.
Is it possible an issue with the collection being too large? It is 30GB with around 40 million documents.

I seem to have been using an old way of specifying the collection name and should have had it in the schema definition: https://mongoosejs.com/docs/guide.html#collection
`

Related

Mongoose fill defaults with aggregate

I'm not sure if this is intentional or not, but I cannot seem to make defaults work for aggregate(). For example, if I add a new field to the schema:
const userSchema = new mongoose.Schema({ sessionIds: { type: [String], default: [] } });
export.User = mongoose.model('User', userSchema);
and run the query on existing documents (which don't have this field yet)
const users = await User.find({}).exec();
console.log(users[0].sessionIds);
This will print an empty array correctly. However, when I run the same query, but using aggregate, it prints undefined.
const users = await User.aggregate({ $match: {} }).exec();
console.log(users[0].sessionIds);
Is there a way I can tell Mongoose to apply the default values for the aggregation or apply it to the results after the aggregation ran?
Edit: After experimenting a bit more, I figured out that it has to do something with aggregate returning lean results, while find returning Mongoose objects. Is there a way to make aggregate return mongoose objects as well?

Indexing items in array - MongoDB

I'm quite new to mongodb, hence I would like to know how the mongoose schema should look like when I need to add indexed items in an array.
Here is how I want the output to look like:
_id: some_id
users: Object
0: Array
0: some_user_id
1: some_user_id
2: some_user_id
This is the schema I tried to create, but I think I'm wrong here:
const mongoose = require('mongoose')
const timerSchema = mongoose.Schema({
users: [[]]
})
module.exports = timerSchema
Thank you in advance!
If you want timerSchema.users property to hold an array of arrays then your schema definition is correct.you can also specify type of array, refer This example to create array of arrays using mongoose Schema which contain output as well.
or if you want users as object then,
const timerSchema = mongoose.Schema({
users: {
<Field1>:[[]],
<Field2>:<Type>
}
})

How to get the defined indexes from Mongoose

I have been trying to find out the indexes which are already created via MongoDB manually( I have created 2d sphere indexes for two fields via mongobooster and creating one via schema by defining it). Now if i run this query in mongodbooster
db.collectionname.getIndexes();
It results me the 3 documents with name.key and which indexes i have used. I want to perform this same operation in mongoose i can't find a equivalent query for the same. I tried this
const indexes = OrderSchema.indexes();
console.log('index:', indexes);
But it gives me only one index which i have defined in schema that is _id i need two other fields as well which contains 2d-sphere index how can i get that too. What am trying to achieve here is if 2d sphere indexes are already created don't create an index else create an index that's all am trying to achieve here. Any help is appreciated Thanks
Yeah, you can't do it with a schema. You will need to create the model first, and then you can do something like this:
Order.collection.getIndexes({full: true}).then(indexes => {
console.log("indexes:", indexes);
// ...
}).catch(console.error);
If you dont have access to mongoose model, but the mongoose connection was created and you need to get the indexes from a collection you can access by this way:
const mongoose = require('mongoose');
mongoose.connect('myConnectionString', { useNewUrlParser: true }).then(() => {
getIndexes();
});
const getIndexes = async () => {
const indexes = await mongoose.connection.db.collection('myCollection').
indexes.forEach(function (index) {
console.log(JSON.stringify(index));
});
};

Mongoose - Defining a model for a preexisting collection

I have imported some CSV data to my database through mongoimport, which created my collection during the import.
When defining my model in Node, what do I pass for the schema parameter? Viewing my db in compass shows a schema already created based off the imported data.
I'm currently passing an empty schema which seems totally wrong.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Units = new Schema({
});
module.exports = mongoose.model('Units', Units, 'units');
The schema should contain something like this that defines the kind of data you're working with.
var Units = new Schema({
f_name: String,
l_name: String,
manager: Boolean
});
See 'Defining your schema'.
Also, I don't believe mongoose.model takes a third parameter.
module.exports = mongoose.model('Units',Units);
Edit: yes it does.

Getting all documents from MongoDB instead of all Models

I'm calling MongoDB from my Node app using Mongoose like this:
var query = itemModel.find();
query.exec(function (err, items) {
console.log(err);
socket.emit("items", items);
});
I have 3 models defined like this:
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var playerModel = require('./models/player.js').make(Schema, mongoose);
var characterModel = require('./models/character.js').make(Schema, mongoose, ObjectId);
var itemModel = require('./models/item.js').make(Schema, mongoose);
my models look like this:
function make(Schema, mongoose) {
itemSchema = new Schema({
name: String
, bonus: [{
type: String
, value: Number
}]
, price: Number
, slot: String
});
return mongoose.model('Character', characterSchema);
}
exports.make = make;
For some reason I'm getting all documents, regardless of them being items, characters or players. Since I'm calling find() on itemModel I was expecting only Items, what am I doing wrong?
The model that you have shown appears to be the item model, but you are creating the model with the 'Character' name. This means that you told Mongoose about the scheme for an item and that it is stored in the 'character' collection. Assuming you've done the same for each other model (Character/Player), you've been Mongoose that everything is in the same collection.
Then you query that collection and you seem surprised that everything is stored in the same collection. It strikes me as if you have little experience with Mongoose/MongoDB, so I will suggest you download and learn to love MongoVUE. This application is a good GUI to see what is going on under the hood of the MongoDB database. While developing, you also might want to enable debugging so you can see what queries mongoose is launching to the server (mongoose.set('debug', true)).

Resources