首页 > 数据库技术 > 详细

MongoDB 搭建Node.js开发环境

时间:2018-03-30 15:38:25      阅读:227      评论:0      收藏:0      [点我收藏+]

理解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开发环境

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!