【问题标题】:Mongoose find() returning array emptyMongoose find() 返回数组为空
【发布时间】:2015-09-21 05:07:00
【问题描述】:

我有以下产品型号:

'use strict';

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

// create a schema
let produtoSchema = new Schema(
    {
        descricao: { type: String, required: true },
        gateways: [ { type : mongoose.Types.ObjectId, ref: 'Gateway' } ]
    }
);

mongoose.model('Produto', produtoSchema);

以下集合:

rs0:PRIMARY> db.produtos.find().pretty()
{
    "_id" : ObjectId("55fef1a3d7c6912033f2da72"),
    "descricao" : "Product description",
    "gateways" : [
        ObjectId("55fee8a97cb7db7740acb322")
    ]
}
rs0:PRIMARY> 

所以,我正在尝试使用 Mongoose 获取特定产品,但“网关”数组为空:

let Produto       = mongoose.model('Produto');
Produto.find(
{
    _id: mongoose.Types.ObjectId("55fef1a3d7c6912033f2da72")

}, function(err, result) 
{
    if (err) console.log(err);

    console.log(result);
});

结果是:

[ { _id: 55fef1a3d7c6912033f2da72,
    descricao: 'Product description',
    gateways: [] } ]

A也试过了,结果一样:

Produto
.find( { _id: mongoose.Types.ObjectId("55fef1a3d7c6912033f2da72") })
.populate('gateways')
.exec(function(err, result) 
{
    if (err) console.log(err);
    console.log(result);
});

知道我做错了什么吗?

谢谢。

【问题讨论】:

  • 尝试使用_id: "55fef1a3d7c6912033f2da72"
  • 同样的结果。我正在获取文档,唯一的问题是 gateway[ ] 数组是空的,而不是 gateway [ ObjectId("55fee8a97cb7db7740acb322") ]

标签: mongodb mongoose


【解决方案1】:

我找到了问题。

我变了:

gateways: [ { type : mongoose.Types.ObjectId, ref: 'Gateway' } ]

通过

gateways: [ { type : mongoose.Schema.ObjectId, ref: 'Gateway' } ]

它们有什么区别?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2013-12-17
    • 2015-08-16
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多