Created
December 17, 2024 19:00
-
-
Save vmetnev/21a3109ed20f1052313d5b736b016132 to your computer and use it in GitHub Desktop.
Dynamic add properties to Mongoose model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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