Monday, April 7, 2014

NodeJs, Mongoose with preexisting data

First we assume there is a collection which is called test in db.test

First we have to create connection

var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
then open the connection and create Schema to match the existing collection's schema, and put the existing collection as the third params in mongoose.model(), like this: mongoose.model('User', userSchema, 'test');
db.once('open', function callback() {
    var userSchema = new mongoose.Schema({
        _id: mongoose.Schema.ObjectId,
        a: Number
    });
    var User = mongoose.model('User', userSchema, 'test');
    User.find(function(err, users){
        if(err) return console.err(err);
        console.log(users);
    })

})
And it is working great.

1 comment:

  1. do all the other query functions e.g(update, delete) work right with this approach?

    ReplyDelete