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

发布于 2024-09-24 00:37:03 字数 927 浏览 10 评论 0原文

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

它根本不起作用。数据库创建正常,但用户名不唯一。对我做错了什么有任何帮助或了解吗?

Update: Been some time. But back then decided not to use Mongoose. Main reason being that we couldn't really come up with a great reason for using an ORM when using mongo and javascript.


I've been trying to create a database/model with Mongoose which is basically just a user database where the username is unique. Sounds simple enough, but for some reason I've been unable to do so.

What I've got so far is this:

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() {});*/

It just doesn't work. The database is created alright, but the username is not unique. Any help or knowledge of what I'm doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

半葬歌 2024-10-01 00:37:04

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

You should define your unique indexes before running your app for the first time. Otherwise, you need to drop your collection and start over. Also, mongoose will not throw an error when you attempt to save { name: 'user1' } when 'user1' already exists.

流年已逝 2024-10-01 00:37:04

Learnboost 最近上传了一组示例 https://github.com/LearnBoost/mongoose/tree/大师/示例

Learnboost recently uploaded a set of examples https://github.com/LearnBoost/mongoose/tree/master/examples

执笔绘流年 2024-10-01 00:37:04

我知道这个问题已有 10 年历史了,最初的发布者放弃了 Mongoose,但由于它突然出现在 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: '[email protected]' });
    await User.create({ name: 'Joe Bloggs', email: '[email protected]' });

    // 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 运行。

I am aware this question is 10 years old and the original poster abandoned Mongoose, but since it pops up near the top of Google searches I felt I would provide a fresh answer.

Providing a complete basic example, using Typescript. I have added comments in the
code, where appropriate.

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: '[email protected]' });
    await User.create({ name: 'Joe Bloggs', email: '[email protected]' });

    // 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)
    });

Note, this was validated with Mongoose 5.9.26, running against Mongo 4.0.13.

↘人皮目录ツ 2024-10-01 00:37:03

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

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

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

    [...]
}));    

You need to define the schema. Try this: (

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

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

    [...]
}));    
蓝天白云 2024-10-01 00:37:03

对于 Mongoose 2.7(在 Node 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 );

    }

  });

});

For Mongoose 2.7 (tested in Node 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 );

    }

  });

});
樱花细雨 2024-10-01 00:37:03

尝试在 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 编译它
祝你好运..

Try giving right path in var mongoose = require('mongoose').Mongoose,

. It worked for me..

#

my code

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() {});

Compile it with node filename.js
good luck..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文