更新: :有一段时间。但是后来决定不使用猫鼬。主要原因是我们实际上无法提出使用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(在节点v。0.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 );

    }

  });

});

尝试在var mongoose中给出正确的路径= require('mongoose')。

. 。它对我有用。

#

我的代码

require.paths.unshift("/home/LearnBoost-mongoose-45a591d/mongoose");
var mongoose = require('mongoose').Mongoose;


var db = mongoose.connect('mongodb://localhost/db');


 mongoose.model('User', {
            properties: ['first name', 'last name', 'age', 'marriage_status', 'details', 'remark'],


});

var User = db.model('User');
var record = new User();

record.first name = 'xxx';
record.last name = 'xxx';
record.age = 'xxx';
record.marriage_status = 'xxx';
record.details = 'xxx';
record.remarks = 'xxx';

record.save(function() {
User.find().all(function(arr) {

   console.log(arr); 
   console.log('length='+arr.length);



});

}); 


//User.remove({}, function() {});

用节点fileName.js对其进行编译好运。

您应该在第一次运行应用程序之前定义唯一索引。否则,您需要放弃收藏并重新开始。另外,当您尝试保存{name:'user1'}时,'user1'已经存在时,Mongoose不会丢失错误。

LearnBoost最近上传了一组示例 https://github.com/learnboost/mongoose/tree/master/examples

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top