更新:已经有一段时间了.但当时决定不使用Mongoose.主要原因是我们在使用mongo和javascript时无法真正想出使用ORM的理由.
我一直在尝试用Mongoose创建一个数据库/模型,它基本上只是一个用户数据库,用户名是唯一的.听起来很简单,但由于某种原因,我一直无法这样做.
到目前为止我得到的是:
var mongoose = require('mongoose').Mongoose, db = mongoose.connect('mongodb://localhost/db'); mongoose.model('User', { properties: [ 'name', 'age' ], cast: { name: String, age: Number }, //indexes: [[{name:1}, {unique:true}]], indexes: [ 'name' ] /*, setters: {}, getters: {}, methods: {} */ }); var User = db.model('User'); var u = new User(); u.name = 'Foo'; u.save(function() { User.find().all(function(arr) { console.log(arr); console.log('length='+arr.length); }); }); /*User.remove({}, function() {});*/
它只是不起作用.数据库创建正常,但用户名不是唯一的.对我做错的任何帮助或了解?
您需要定义架构.试试这个: (
var mongoose = require('mongoose').Mongoose, db = mongoose.connect('mongodb://localhost/db'), Schema = mongoose.Schema; mongoose.model('User', new Schema({ properties: [ 'name', 'age' ], [...] }));
对于Mongoose 2.7(在Node v.8.8中测试):
var mongoose = require('mongoose'), Schema = mongoose.Schema; var db = mongoose.connect('mongodb://localhost/db'); var User = new Schema({ first_name: String, last_name: String }); var UserModel = mongoose.model('User', User); var record = new UserModel(); record.first_name = 'hello'; record.last_name = 'world'; record.save(function (err) { UserModel.find({}, function(err, users) { for (var i=0, counter=users.length; i < counter; i++) { var user = users[i]; console.log( "User => _id: " + user._id + ", first_name: " + user.first_name + ", last_name: " + user.last_name ); } }); });