標籤:taobao 分享 document find mil install 微軟雅黑 any def
理解Mongoose
Elegant MongoDB object modeling for Node.js
?
安裝Mongoose
?
$ cnpm install --save mongoose
?
$ cnpm install --save-dev typescript @types/node @types/mongoose
?
源碼參考
import { Document, model, Model, Schema, connect } from‘mongoose‘;
?
console.log(‘hello mongodb!‘);
?
var UserSchema: Schema = new Schema({
username: {
type: String,
required: true,
unique: true
},
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
?
?
?
MongoDB 搭建Node.js開發環境