MongoDB 搭建Node.js開發環境

理解Mongoose

Elegant MongoDB object modeling for Node.js html

 

安裝Mongoose

 

$ cnpm install --save mongoose node

 

$ cnpm install --save-dev typescript @types/node @types/mongoose git

 

源碼參考

import { Document, model, Model, Schema, connect } from 'mongoose'; github

 

console.log('hello mongodb!'); mongodb

 

var UserSchema: Schema = new Schema({ typescript

username: { npm

type: String, mongoose

required: true, ide

unique: true ui

},

age: Number,

friends: [String],

data: [Schema.Types.Mixed]

});

 

interface IUser extends Document {

username: string;

age: number;

friends: string[];

data: any[];

}

 

var UserModel: Model<IUser> = model<IUser>('User', UserSchema);

 

var connectUri = 'mongodb://localhost/testdb';

connect(connectUri, function (error) {

if (error) {

console.log(error.message);

}

 

});

 

var user = new UserModel({ name: 'bob' });

user.username = "bob";

user.age = 38;

user.friends = ["tom", "cat", "jerry", "mouse"];

user.data = [123, "abc"];

user.save().then(()=>{

 

UserModel.findOne({}, (err: any, user: IUser) => {

console.log("user: %s", user);

});

 

})

 

 

 

參考資源

http://mongoosejs.com/

http://mongoosejs.com/docs/guide.html

https://npm.taobao.org/package/mongoose

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mongoose/v4

相關文章
相關標籤/搜索