寻找猫鼬“你好世界”的例子

时间:2010-09-14 09:29:45

标签: javascript mongodb mongoose

更新:已经有一段时间了。但当时决定不使用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() {});*/

它不起作用。数据库创建正常,但用户名不是唯一的。对我做错的任何帮助或了解?

6 个答案:

答案 0 :(得分:15)

您需要定义架构。试试这个:(

var mongoose = require('mongoose').Mongoose,
db = mongoose.connect('mongodb://localhost/db'),
Schema = mongoose.Schema;

mongoose.model('User', new Schema({
    properties: [
        'name',
        'age'
    ],

    [...]
}));    

答案 1 :(得分:6)

对于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 );

    }

  });

});

答案 2 :(得分:3)

尝试在var mongoose = require('mongoose')中给出正确的路径.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() {});

使用node filename.js编译它 祝你好运..

答案 3 :(得分:1)

您应该在首次运行应用之前定义唯一索引。否则,您需要删除您的收藏并重新开始。此外,当'user1'已经存在时,当您尝试保存{name:'user1'}时,mongoose不会抛出错误。

答案 4 :(得分:1)

答案 5 :(得分:0)

我知道这个问题已有10年了,最初的海报被废弃了猫鼬,但是由于它出现在Google搜索的顶部附近,所以我想提供一个新的答案。

使用Typescript提供完整的基本示例。我已经在 代码。

async function mongooseHelloWorld () {
    const url = 'mongodb://localhost/helloworld';

    // provide options to avoid a number of deprecation warnings
    // details at: https://mongoosejs.com/docs/connections.html
    const options = {
        'useNewUrlParser': true,
        'useCreateIndex': true,
        'useFindAndModify': false,
        'useUnifiedTopology': true
    };

    // connect to the database
    console.log(`Connecting to the database at ${url}`);
    await mongoose.connect(url, options);

    // create a schema, specifying the fields and also
    // indicating createdAt/updatedAt fields should be managed
    const userSchema = new mongoose.Schema({
        name:{
            type: String,
            required:true
        },
        email: {
            type: String,
            required: true
        }
    }, {
        timestamps: true
    });

    // this will use the main connection. If you need to use custom
    // connections see: https://mongoosejs.com/docs/models.html
    const User = mongoose.model('User', userSchema);

    // create two users (will not be unique on multiple runs)
    console.log('Creating some users');
    await User.create({ name: 'Jane Doe', email: 'jane.done@example.abcdef' });
    await User.create({ name: 'Joe Bloggs', email: 'jane.done@example.abcdef' });

    // Find all users in the database, without any query conditions
    const entries = await User.find();
    for (let i = 0; i < entries.length; i++) {
        const entry = entries[i] as any;
        console.log(`user: { name: ${entry.name}, email: ${entry.email} }`);
    }
}

// running the code, and making sure we output any fatal errors
mongooseHelloWorld()
    .then(() => process.exit(0))
    .catch(error => {
        console.log(error)
    });

请注意,这已经在Mongoose 5.9.26上进行了验证,并且可以在Mongo 4.0.13上运行。