MongoDB 搭建Node.js开发环境
Posted 抱影无眠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB 搭建Node.js开发环境相关的知识,希望对你有一定的参考价值。
理解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/docs/guide.html
https://npm.taobao.org/package/mongoose
https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mongoose/v4
以上是关于MongoDB 搭建Node.js开发环境的主要内容,如果未能解决你的问题,请参考以下文章
node.js操作数据库之MongoDB+mongoose篇