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 is a brand new universally unique ID.
Another question asks about creating an ObjectId from an existing string representation. In this case, you already have a string representation of an ID—it may or may not be universally unique—and you are parsing it into an ObjectId.
You can find the ObjectId constructor on require('mongoose').Types. Here is an example:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
id is a newly generated ObjectId.
Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:
var id = new mongoose.Types.ObjectId();
You can read more about the Types object at Mongoose#Types documentation.
You can create a new MongoDB ObjectId like this using mongoose:
var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
I needed to generate mongodb ids on client side.
After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectid being even lighter
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');
Related
I have a problem when adding data to my User class by Mongoose that can't update it later by parse API.
I've found that's because of mongoose use ObjectId for _id field and parse just work with plain string as ObjectId.
The question is how can I set my custom unique plain string as ObjectId in Parse Server object creation?
You can do it like this:
const cryptoUtils = require('parse-server/lib/cryptoUtils');
const id = cryptoUtils.newObjectId();
Source: https://github.com/parse-community/parse-server/blob/master/src/cryptoUtils.js
I can't figure out the difference between mongo ObjectID & ObjectId.
The document said ObjectId, but when I read the code, I see
import { ObjectID } from 'bson';
To make things even more confused is the mongoose document & code.
The mongoose also says ObjectId http://mongoosejs.com/docs/api.html#types-objectid-js. But when I read the codes I saw
// mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is
// commonly used in mongoose and is found in an example in the docs:
// http://mongoosejs.com/docs/api.html#aggregate_Aggregate
// constructor exposes static methods of mongodb.ObjectID and ObjectId(id)
type ObjectIdConstructor = typeof mongodb.ObjectID & {
(s?: string | number): mongodb.ObjectID;
}
So what exactly is the difference between ObjectID, ObjectId and mongoose ObjectId?
I found there was another SO talking about this BSON::ObjectId vs Mongo::ObjectID
The links there were dead though and it didn't take about mongoose. So I hope my question won't be marked as duplicated.
Mongo ObjectID is a unique 12-byte identifier which can be generated by MongoDB as the primary key.
An ObjectID is a unique, not null integer field used to uniquely identify rows in tables
In Mongoose ObjectID is same as Mongo ObjectID and referencing an object in another 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.
I understand what is the use of Schema and model in mongoose, however when defining/creating a new Schema there are 2 ways of doing it (that I found of), and I'm confused by it,
1st way (without new - no instance created):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');
// No 'new' keyword
var mySchema = mongoose.Schema({
parameter1 : String,
parameter2 : String
});
var modelName = mongoose.model('collectionName', mySchema);
and 2nd way of doing it (with new - an instance created):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');
// There is 'new' keyword
var mySchema = new mongoose.Schema({
parameter1 : String,
parameter2 : String
});
var modelName = mongoose.model('collectionName', mySchema);
What's the differences between the two? when to use one or the other?
Both way are fine, but according to code standard and mongoose library, we use 2nd way. It's follow extending & Implementation feature like OOP.
Schema & Model we use in nodejs for validation & restrict unwanted object & fields inserting into mongo collection.
Thats the reason for uses.
I am working on Mongoose plugin that have to access existing model and create similar schema as previous model and fix some attributes and add some custom properties. How to do such cloning of scheme? I tried but its not working:
var mongoose = require('mongoose');
var mainSchema = new mognoose.schema({'prop' : String});
var anotherSchema = new mongoose.schema(mainSchema);
Of course, its not working at all and I can't find any solution in API doc and source code (as far I can read that code).
For anyone googling, try:
schema.clone();
This creates a full copy of the schema, so you can add more properties, multiple discriminators, etc.
http://mongoosejs.com/docs/api.html#schema_Schema-clone
Assign the schema to a regular object first:
var mongoose = require('mongoose');
var schemaObj = {'prop' : String}
var mainSchema = new mongoose.Schema(schemaObj);
var anotherSchema = new mongoose.Schema(schemaObj);