我有一个node.js应用程序,它提取一些数据并将其粘贴到一个对象中,就像这样:

var results = new Object();

User.findOne(query, function(err, u) {
    results.userId = u._id;
}

当我基于存储的ID执行if/then时,比较永远不会为真:

if (results.userId == AnotherMongoDocument._id) {
    console.log('This is never true');
}

当我对这两个id执行console.log时,它们完全匹配:

User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002

我假设这是某种数据类型问题,但我不确定如何转换结果。userId转换为一个数据类型,这将导致上述比较是正确的,我的外包大脑(又名谷歌)一直无法提供帮助。

我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。

我有一个叫做people的mongodb集合 其架构如下:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

现在,我有一个非常基本的快速应用程序连接到数据库,并成功地创建“人”与一个空的朋友数组。

在应用程序的次要位置,有一个添加好友的表单。表单接收firstName和lastName,然后是带有名称字段的POSTs,同样用于引用适当的people对象。

我有一个困难的时间做的是创建一个新的朋友对象,然后“推”到朋友数组。

我知道当我通过mongo控制台这样做时,我使用$push作为查找标准后的第二个参数的更新函数,但我似乎找不到合适的方法让猫鼬这样做。

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

如果您有子文档数组,Mongoose会自动为每个子文档数组创建id。例子:

{
    _id: "mainId"
    subDocArray: [
      {
        _id: "unwantedId",
        field: "value"
      },
      {
        _id: "unwantedId",
        field: "value"
      }
    ]
}

是否有一种方法告诉猫鼬不为数组中的对象创建id ?

下面是我的用户模式在user.js模型-

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
        email : { type: String, require: true, unique: true },
        password: { type: String, require:true },
    },
    facebook: {
        id           : { type: String },
        token        : { type: String },
        email        : { type: String },
        name         : { type: String }
    }
});

var User = mongoose.model('User',userSchema);

module.exports = User;

这就是我在控制器中使用它的方式

var user = require('./../models/user.js');

这就是我在数据库中保存它的方式

user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
    if(err)
        res.send(err);
    else {
        console.log(result);
        req.session.user = result;
        res.send({"code":200,"message":"Record inserted successfully"});
    }
});

错误- - - - - -

{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : null }"} 

我检查了db集合,没有这样的重复条目存在,让我知道我做错了什么?

供您参考- req.body.email和req.body.password是抓取值。

我也检查了这篇文章,但没有帮助

如果我完全删除,然后它插入文档,否则它抛出错误“重复”错误,即使我在local.email中有一个条目

我有一个_ids数组,我想相应地获取所有文档,最好的方法是什么?

就像……

// doesn't work ... of course ...

model.find({
    '_id' : [
        '4ed3ede8844f0f351100000c',
        '4ed3f117a844e0471100000d', 
        '4ed3f18132f50c491100000e'
    ]
}, function(err, docs){
    console.log(docs);
});

该数组可能包含数百个_id。

下面是我的代码

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

var Cat = mongoose.model('Cat', {
    name: String,
    age: {type: Number, default: 20},
    create: {type: Date, default: Date.now} 
});

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

我已经在我的mongo数据库中有一些记录,我想运行这段代码来更新年龄为17岁的名称,然后在代码的末尾打印结果。

然而,为什么我仍然从控制台得到相同的结果(不是修改后的名称),但当我进入mongo db命令行并键入“db.cats.find();”。结果是修改后的名称。

然后我返回去再次运行这段代码,结果被修改了。

我的问题是:如果数据被修改了,那么为什么我仍然在console.log它的第一时间得到原始数据。

我使用Mongoose版本3和MongoDB版本2.2。我注意到一个__v字段已经开始出现在我的MongoDB文档。这与版本控制有关吗?它是如何使用的?

也许是时间的问题,也许是我淹没在稀疏的文档中,无法理解Mongoose中的更新概念:)

事情是这样的:

我有一个联系模式和模型(缩短属性):

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var mongooseTypes = require("mongoose-types"),
    useTimestamps = mongooseTypes.useTimestamps;


var ContactSchema = new Schema({
    phone: {
        type: String,
        index: {
            unique: true,
            dropDups: true
        }
    },
    status: {
        type: String,
        lowercase: true,
        trim: true,
        default: 'on'
    }
});
ContactSchema.plugin(useTimestamps);
var Contact = mongoose.model('Contact', ContactSchema);

我从客户端收到一个请求,包含我需要的字段,然后使用我的模型:

mongoose.connect(connectionString);
var contact = new Contact({
    phone: request.phone,
    status: request.status
});

现在问题来了:

If I call contact.save(function(err){...}) I'll receive an error if the contact with the same phone number already exists (as expected - unique) I can't call update() on contact, since that method does not exist on a document If I call update on the model: Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...}) I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter. If I do the same, but in the second parameter I pass an associative array of the request properties {status: request.status, phone: request.phone ...} it works - but then I have no reference to the specific contact and cannot find out its createdAt and updatedAt properties.

因此,我的底线是:给定一个文档联系人,如果它存在,我如何更新它,如果它不存在,我如何添加它?

谢谢你的时间。

如果我有这种图式。

person = {
    name : String,
    favoriteFoods : Array
}

... 其中favoriteFoods数组用字符串填充。我怎样用猫鼬找到所有喜欢吃“寿司”的人?

我希望你能说出这样的话:

PersonModel.find({ favoriteFoods : { $contains : "sushi" }, function(...) {...});

(我知道mongodb中没有$contains,只是解释了我在知道解决方案之前希望找到什么)