Mongoose _id to unit64 - node.js

I need a unit64 ID in my MongoDB database. ObjectIds are 96 bits.
I have seen the answer here that one way to do it is to add a few constant characters to the beginning of the ID. But how d I achieve this in Mongoose?
Suppose that I have a schema like this:
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
_id: {
???
},
});

I ended up using nanoid for now:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { customAlphabet } = require('nanoid');
const alphabet = '123456789';
const nanoid = customAlphabet(alphabet, 19); //from 11...111 to 99...999
const mySchema = new Schema({
int_id: {
type: String,
unique: true,
default: () => nanoid()
},
});

Related

Mongoose model stuck in an infinite loop - Node

I'm setting up a basic schema for my mongo db, and when representing the schema as a variable, I get stuck in an infinite loop that logs const mongoose = require('mongoose') when using .load in node.
When I use the schema as an argument to the mongoose.model() function, the file is able to load perfectly fine in node.
This is what is creating the infinite loop -
const mongoose = require('mongoose');
mongoose.set('strictQuery', false)
mongoose.connect('mongodb://127.0.0.1:27017/test');
let movie = new mongoose.Schema({
title: String,
score: Number,
year: Number
});
const Movie = mongoose.model('Movie', movie);
This is what is working perfectly fine -
const mongoose = require('mongoose');
mongoose.set('strictQuery', false)
mongoose.connect('mongodb://127.0.0.1:27017/test');
const Movie = mongoose.model('Movie', { title: String, score: Number, year: Number });
This is the correct way to define schema
var mongoose = require("mongoose")
const movie = new mongoose.Schema({
title: {
type: String,
},
score: {
type: Number,
},
year: {
type: Number,
}
})
module.exports = mongoose.model("Movie", movie)

How do I update the existing documents' schema?

I'm using mongoose to do some MongoDB operations.
At the beginning the category was number,
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: Number,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
Now the category changed to String, So I changed the model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
category: {
type: String,
}
})
module.exports = mongoose.model("SampleSchema", sampleSchema);
The problem is, I have already inserted 200 records into this collection. Is there any way to update the category value with a string and change its type to string?
Please get All data by query and update it one by one in loop.
Like:
db.tableName.find( { 'status' : { $type : 1 } } ).forEach( function (val) {
val.status = new String(val.status);
db.tableName.save(val);
});
I changed the category to mixed, that's working fine with numbers and string.
Thanks for the help #prasad_

Mongoose Find By Ref ID

so I have two schemas, User und Company
const UserSchema = new mongoose.Schema({
_createdAt: Date,
company: {type: mongoose.Schema.Types.ObjectId, ref: 'company'},
email: String,
});
const CompanySchema = new mongoose.Schema({
_createdAt: {
type: Date,
required: true
},
name: {
type: String,
required: true
}
});
const userModel = mongoose.model("user", UserSchema, "user");
const companyModel = mongoose.model("company", CompanySchema, "company");
I would now like to query for a specific User by his Company _id, but for some reason this is not working, it returns an empty array even though I have a user with the exact company ObjectId in my Database.
userModel.find({company: "5cfa4352ffc1c8135d8276a4"})
.exec((err, user) => {
console.log(user);
}
In my mongo shell the command
db.user.find({company: "5cfa4352ffc1c8135d8276a4"})
returns the users as expected so why does this not work in mongoose? Thanks in advance
Try this
const ObjectId = require('mongodb').ObjectID;
then
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
I hope it will work
If you want to find by that id you probably need to do this:
const mongojs = require('mongojs');
const ObjectId = mongojs.ObjectId;
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
Since you are using moongose, you can get the ObjectId like this:
const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')

Mongoose Populate cant get this to work?

book.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const BookSchema = new Schema({
name: {
type: String,
required: true
}
})
module.exports = BookSchema
book.model.js
const mongoose = require('mongoose')
const BookSchema = require('../schema/book.schema')
const Book = mongoose.model('Book', BookSchema)
module.exports = Book
novel.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const NovelSchema = new Schema({
name: {
type: String,
required: true
},
type: {
type: Schema.Types.ObjectId,
ref: 'Book'
}
})
module.exports = NovelSchema
novel.model.js
const mongoose = require('mongoose')
const NovelSchema = require('../schema/novel.schema')
const Novel = mongoose.model('Novel', NovelSchema)
module.exports = Novel
query
// Mongoose Populate cant get this to work
// I am at a loss
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'books'
})
mongoose populate not working。
Please let me know what I am doing wrong or give me a simple explanation...Thank you...
You are right to use the populate for loading the subdocument, but you need to pass the name of the book field in the novel schema, in your case the name is type.
Here is the link to documentation with some examples: Mongoose Populate
And below is the more one solution to your problem:
let book = await new BookModel({name:"book test"}).save();
console.log('-----------BOOK ITEM-------------');
console.log(book);
let novel = await new NovelModel({name:"novel test",type:book._id}).save();
console.log('-----------NOVEL ITEM-------------');
console.log(novel);
let itemPopulated = await NovelModel.findById(novel._id)
.populate('type')
.then((result) => {
return result;
}).catch((err) => {
console.log(err);
});
console.log('-----------ITEM POPULATED-------------');
console.log(itemPopulated);
And the execution output:
The parameter on the function populate() is the path of the field you want to populate, and also when you use populate or any chained function in mongoose you have to use the exec() function in the ending, so the correct way to do it would be:
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'type'
}).exec()

Mongoose : Types referring to other models

I've this:
models/record.js
var mongoose = require("mongoose");
var RecordSchema = new mongoose.Schema({
address : require("./address").Address
});
var Record = mongoose.model('Record', RecordSchema);
module.exports = {
Record: Record
}
models/address.js
var mongoose = require("mongoose");
var AddressSchema = new mongoose.Schema(
{
streetLine1: String,
streetLine2: String,
city: String,
stateOrCounty: String,
postCode: String,
country: require("./country").Country
});
var Address = mongoose.model('Address', AddressSchema);
module.exports = {
Address: Address
}
models/country.js
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
var Country = mongoose.model('Country', CountrySchema);
module.exports = {
Country: Country
}
It's actually showing this error:
TypeError: Undefined type Model at country
Did you try nesting Schemas? You can only nest using refs or arrays.
I am trying to create a model where few types is another model. How to archive this ?
The problem here is that you are exporting a model from country.js and using the same by requiring in the address schema creation. While creating nested schemas, the value for a property should be a schema Object and not a model.
Change your country.js to:
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
module.exports = {
Country: CountrySchema
}

Resources