码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB 搭建Node.js开发环境

时间:2018-03-30 16:18:54      阅读:149      评论:0      收藏:0      [点我收藏+]

标签: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开发环境

标签:taobao   分享   document   find   mil   install   微软雅黑   any   def   

原文地址:https://www.cnblogs.com/xiaobo/p/8676358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!