Skip to content

Instantly share code, notes, and snippets.

@vmetnev
Created December 17, 2024 19:00
Show Gist options
  • Save vmetnev/21a3109ed20f1052313d5b736b016132 to your computer and use it in GitHub Desktop.
Save vmetnev/21a3109ed20f1052313d5b736b016132 to your computer and use it in GitHub Desktop.
Dynamic add properties to Mongoose model
// Object to new mongoose schema and to save data in mongoDB from provided instance of an object
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
mongoose.set("strictQuery", false);
const database = {
uri: "mongodb://127.0.0.1:27017/",
name: "dayalayer",
user: "",
password: "",
options: {},
};
function mongooseConnect() {
mongoose.connect(`${database.uri}${database.name}`, database.options).then(
() => {
console.log("Mongo connected...")
listCollections()
},
err => {
console.error(err)
}
)
}
mongooseConnect()
const fruitSchema = new Schema({}, {
strict: false // to allow adding fields to the schema after creating the model
})
const Fruit = mongoose.model('fruit', fruitSchema)
let fruitInstance = {
name: "apple",
color: "red",
price: 1200
}
for (let Key in fruitInstance) {
fruitSchema.add({
[Key]: {
type: typeof fruitInstance[Key],
}
})
}
// fruitSchema.add({
// other: String
// }) ===>>> if you want to add a field to the schema after creating the model
fruitInstance.other = "other"
fruitInstance.another = "another"
let one = new Fruit(fruitInstance, {
strict: false
})
one.save()
async function listCollections() {
let db = mongoose.connection.db;
const collections = await db.listCollections().toArray();
collections.forEach((collection) => console.log(collection.name));
db = mongoose.connection.db;
await db.collection("popcorn").rename("popcorn1").catch(error => console.log(error.codeName))
mongoose.disconnect();
}
// mongoose.connection.close()
// models with individual collection name from set schema
//const TickerModel = mongoose.model('tickerdata2024-02-28', require('../Models/TickerSchema'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment