简体   繁体   中英

Mongoose Database Connection and Schema

Hi There: I'm having a difficult time online finding out how to perform a simple database connection, schema creation, and basic CRUD using mongoose with node.js. Right now I have the following code but am getting the error:

"TypeError: object is not a function

at Schema.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native).."

// Launch express and server
var express = require('express');
var app = express.createServer();


//connect to DB
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/napkin_0.1');


// Define Model
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

User = new Schema({
  'title': { type: String, index: true },
  'data': String,
  'tags': [String],
  'user_id': ObjectId
});

//Define Collection
mongoose.model('Document', User);


var user = new User();
user.title = "TEST TITLE";
user.save();


//Launch Server
app.listen(3002);

You are trying to instantiate an instance of the Schema. I would change

User = new Schema({

To

UserSchema = new Schema({

and later on call

var User = mongoose.model('user', UserSchema);

and finally

var user = new User();

After your schema definition.

//Define Collection
mongoose.model('Document', User);

The above code is not for defining collection, it is to initialize the model object.

Change it as follows:

//Create Model Object
var UserModel = mongoose.model('user_model_name', User); // 2nd param -> User is a schema object

Then create the Document object out of model object. As follows:

var user_doc = new UserModel();

Then you can use getters/setters and methods.

user_doc.title = 'your text for title';
user_doc.save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM