Is there a way to clone a collection or entire Mongodb database (my databases only have one collection so both options are OK) with Mongoose? I saw that there is a possibility to execute raw Mongo commands with Mongoose. What command can I use to clone an entire collection or db from one db to another?
Thanks in advance.
I had a hard time doing this I don't have any reference.
However, this is how I did on my end.
1, I created another collection within the same
db: mydb
collections: books, oldbooks
2, Since I only know how to connect to one database at a time, I stick to this:
mongoose.connect(process.env.CONN_STR);
3, On your existing collection, in this case, books, we have this code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var BookSchema = new Schema({
name: String
})
module.exports = mongoose.model('Book', BookSchema);
4, I created a different Schema for the backup so I can specific the name of the collection:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var BackupSchema = new Schema({
name: String
}, {
collection: 'oldbooks'
})
module.exports = mongoose.model('BackupBook', BackupBookSchema);
NOTICE: that we specified the collection in BackupBook Schema collection: 'oldbooks'. The idea is to replicate the existing schema to the backup schema.
5, Fetch and save each entry in the collection:
Book.find()
.exec((err, books) => {
if(err) throw err
else {
books.forEach( (book) => {
var backup = new BackupBook();
backup._id = book._id;
backup.name = book.name;
backup.save((err, backup) => {
})
})
}
})
TLDR: Create a different collection as backup. Query each entry of the collection then save to the backup Schema individually. Note, the backup schema must specify the name of the collection.
Related
var mongoose=require('mongoose');
var GeoJSON = require('mongoose-geojson-schema');
var db = require('./connection.js');
const Schema = mongoose.Schema;
const senuSchema = new Schema({
type:mongoose.Schema.Types.FeatureCollection,
name:String,
crs:Object,
features:Array
});
const model = db.model('senu', senuSchema, 'senu');
console.log('succefully made model');
model.findOne({name:'senu'},function(err,doc){
if (err){console.log(err);}
else{
console.log(doc);
}
});
The code gets a mondodb database connection then I create a model for the data I'm trying to retrieve but when I run it, i get the whole object.
I would like to query for a specific feature within the object which is in a features array in the object.
So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.
Hi everyone this is the first time I ask a question in here,
I'm very new into the MEAN stack and by now I'm trying to develop an application using it. As I understand in mongodb an Schema (Database) can have one or more collections (Tables(?)), when I'm using mongoose I define a Song model and an Artist model:
For Song:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var songSchema = new Schema({
songName: { type: String },
songArtist: [{type : Schema.Types.ObjectId, ref : 'Artist'}]
});
module.exports = mongoose.model('Song', songSchema);
For artist:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var artistSchema = new Schema({
artistName: { type: String }
});
module.exports = mongoose.model('Artist', artistSchema);
My app.js looks like this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/song', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
var models = require('./models/song')(app, mongoose);
The issue with this is, as I understand and saw, that I'm creating 2 databases/schemas while I want to Create one database/schema and have this two collections in there:
SongDatabase:
--- Song
--- Artist
How should I do it in this case with my mongoose models/controllers and my app.js? Thanks in advance :)
I solved all my doubts taking a look into this tutorial, as you can see in here they implement two collections within one database (My inicial concern). Once you are connected to the database and you perform a post to the collection you want, in this case thread or post, it will create the collection into mongodb.
The issue there is that your connection string is mongodb://localhost/song
Song becomes your DB, and within Song you should be able to see two collections
- SongS
- ArtistS
Posible solutions: Flush the database, drop all. Start clean and check what your application is doing. Use another name for the DB
is it possible to reference a sub document schema in mongoose ?
just like below
var sectionSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true}
});
var courseSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true},
sections:[sectionSchema]
});
var studentSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true},
course:{type:mongoose.Schema.Types.ObjectId,ref: 'courseSchema'},
section:{type:mongoose.Schema.Types.ObjectId,ref: 'sectionSchema'},
contactnumber:{type:String,required:true},
parentname:{type:String,required:true}
});
var schoolSchema = mongoose.Schema(
{
id:{type:String,required:true},
name:{type:String,required:true,unique:true},
address:{type:String,required:true},
year:{type:String,required:true},
contactnumber:{type:String,required:true},
courses:[courseSchema],
students:[studentSchema]
});
var School = mongoose.model('School',schoolSchema);
in the above model i have section inside course which is inside school document.
i have students schema which is inside school document i want course to point to course schema and section to point to section schema.so is it possible to refer a sub document schema in mongoose.
For example, I have user collection in db:
{'_id':0, 'name': 'Joe', 'score':[80, 33]}
{'_id':1, 'name': 'Moe', 'score':[90, 81]}
... ...
How can I read this data with existing format, which means, use it's existing schema without create a new one.
I read Mongoose doc and googled for a while but didn't find satisfied answer.
When using mongoose with an existing collection, you have to reference the collection in your mongoose schema. The way to do this is to add the name of the collection to your schema. So if your collection is in 'mongodb://localhost:27017/test' and called 'things', you would use:
~~~
const Schema = mongoose.Schema;
const ThingSchema = new Schema({
name: {
type: String
}
});
const Model = mongoose.model('Thing', ThingSchema, 'things');
module.exports = Model;
~~~
Thanks to http://chrisflx.blogspot.fr/2014/04/nodejs-mongoose-with-preexisting-data.html?m=1
It will work if you make a model with the same schema.
var schema = new mongoose.Schema({ name: 'string', score: [] });
var user = mongoose.model('User', schema);
Edit:
Mongoose is an ODM, so you need a schema to create objects. If you need to run queries and get raw data from the database, I would stick with this library:
https://github.com/mongodb/node-mongodb-native