Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Mongoose "hello world" example

Update: Been some time. But back then decided not to use Mongoose. Main reason being that we couldn't really come up with a great reason for using an ORM when using mongo and javascript.


I've been trying to create a database/model with Mongoose which is basically just a user database where the username is unique. Sounds simple enough, but for some reason I've been unable to do so.

What I've got so far is this:

var mongoose = require('mongoose').Mongoose,
    db = mongoose.connect('mongodb://localhost/db');

mongoose.model('User', {
    properties: [
        'name',
        'age'
    ],

    cast: {
        name: String,
        age: Number
    },

    //indexes: [[{name:1}, {unique:true}]],
    indexes: [
        'name'
    ]
    /*,
    setters: {},
    getters: {},
    methods: {}
    */
});    

var User = db.model('User');

var u = new User();
u.name = 'Foo';

u.save(function() {
    User.find().all(function(arr) {
        console.log(arr);
        console.log('length='+arr.length);
    });
});
/*User.remove({}, function() {});*/

It just doesn't work. The database is created alright, but the username is not unique. Any help or knowledge of what I'm doing wrong?

like image 967
freeall Avatar asked Sep 14 '10 09:09

freeall


People also ask

What is Mongoose model explain with example?

A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What does find do in mongoose?

The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).

Why is Mongoose used?

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema.

Can I use mongoose in Python?

It is impossible because python and nodejs are 2 different runtimes - separate isolated processes which don't have access to each other memories. Mongoose is a nodejs ORM - a library that maps Javascript objects to Mongodb documents and handles queries to the database. All mongoose hooks belong to javascript space.


3 Answers

I am aware this question is 10 years old and the original poster abandoned Mongoose, but since it pops up near the top of Google searches I felt I would provide a fresh answer.

Providing a complete basic example, using Typescript. I have added comments in the code, where appropriate.

async function mongooseHelloWorld () {
    const url = 'mongodb://localhost/helloworld';

    // provide options to avoid a number of deprecation warnings
    // details at: https://mongoosejs.com/docs/connections.html
    const options = {
        'useNewUrlParser': true,
        'useCreateIndex': true,
        'useFindAndModify': false,
        'useUnifiedTopology': true
    };

    // connect to the database
    console.log(`Connecting to the database at ${url}`);
    await mongoose.connect(url, options);

    // create a schema, specifying the fields and also
    // indicating createdAt/updatedAt fields should be managed
    const userSchema = new mongoose.Schema({
        name:{
            type: String,
            required:true
        },
        email: {
            type: String,
            required: true
        }
    }, {
        timestamps: true
    });

    // this will use the main connection. If you need to use custom
    // connections see: https://mongoosejs.com/docs/models.html
    const User = mongoose.model('User', userSchema);

    // create two users (will not be unique on multiple runs)
    console.log('Creating some users');
    await User.create({ name: 'Jane Doe', email: '[email protected]' });
    await User.create({ name: 'Joe Bloggs', email: '[email protected]' });

    // Find all users in the database, without any query conditions
    const entries = await User.find();
    for (let i = 0; i < entries.length; i++) {
        const entry = entries[i] as any;
        console.log(`user: { name: ${entry.name}, email: ${entry.email} }`);
    }
}

// running the code, and making sure we output any fatal errors
mongooseHelloWorld()
    .then(() => process.exit(0))
    .catch(error => {
        console.log(error)
    });

Note, this was validated with Mongoose 5.9.26, running against Mongo 4.0.13.

like image 199
Andre M Avatar answered Oct 25 '22 19:10

Andre M


You need to define the schema. Try this: (

var mongoose = require('mongoose').Mongoose,
db = mongoose.connect('mongodb://localhost/db'),
Schema = mongoose.Schema;

mongoose.model('User', new Schema({
    properties: [
        'name',
        'age'
    ],

    [...]
}));    
like image 22
evilcelery Avatar answered Oct 25 '22 19:10

evilcelery


For Mongoose 2.7 (tested in Node v. 0.8):

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

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

var User = new Schema({
  first_name: String,
  last_name: String
});

var UserModel = mongoose.model('User', User);

var record = new UserModel();

record.first_name = 'hello';
record.last_name = 'world';

record.save(function (err) {

  UserModel.find({}, function(err, users) {

    for (var i=0, counter=users.length; i < counter; i++) {

      var user = users[i];

      console.log( "User => _id: " + user._id + ", first_name: " + user.first_name + ", last_name: " + user.last_name );

    }

  });

});
like image 35
jksdua Avatar answered Oct 25 '22 21:10

jksdua