标签: mongoose-populate

填充中的排序不起作用(猫鼬)

我的MongoDB版本是3.2,mongoose版本是4.6.0

这些是我的架构:

// chat
const chatSchema = new mongoose.Schema({
  users: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }],
  lastMessage:  { type: mongoose.Schema.Types.ObjectId, ref: 'Message' }
});
export const ChatModel = mongoose.model('Chat', chatSchema);

// message
const messageSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  chat: { type: mongoose.Schema.Types.ObjectId, ref: 'Chat', required: true },
  text: { type: String, required: true },
  timestamp: { type: Date, default: Date.now }
});
export const MessageModel = mongoose.model('Message', messageSchema);
Run Code Online (Sandbox Code Playgroud)

我想根据 lastMessage …

sorting mongoose mongodb mongodb-query mongoose-populate

2
推荐指数
1
解决办法
4913
查看次数

猫鼬中的深层种群

我有两个模式,

一个用于用户,另一个用于发布

在用户模式中,我有一个 latestPost 属性,它是 post 模式中条目的 ObjectId

当我加载用户对象时,

我想将 lastestPost 作为一个对象,其中包含来自用户架构的作者用户名,其中作者是一个与用户架构中的 _id 字段匹配的 ObjectId。

猫鼬教程似乎使用的语法

User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})
Run Code Online (Sandbox Code Playgroud)

但它不起作用

它显示

{ _id: 58f54fa51febfa307d02d356,
  username: 'test',
  email: 'test@test',
  firstName: 'test',
  lastName: 'test',
  __v: 0,
  latestPost:
   { _id: 58f54fa51febfa307d02d357,
     user: 58f54fa51febfa307d02d356,
     author: 58f54fa51febfa307d02d356,
     date: 2017-04-17T23:28:37.960Z,
     post: 'Test',
     __v: 0 } }
Run Code Online (Sandbox Code Playgroud)

但我想让它显示

  latestPost:
   { 
     author:  {
      username  : something
     }
   }
Run Code Online (Sandbox Code Playgroud)

如何做这样的事情?模式或查询的设计有问题吗?

User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongodb-query mongoose-populate

2
推荐指数
1
解决办法
2812
查看次数

如何在考虑Mongoose Node.js中的引用的情况下删除对象?

这是我的MongoDB模式:

var partnerSchema = new mongoose.Schema({
    name: String,
    products: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Product'
        }]
});

var productSchema = new mongoose.Schema({
    name: String,
    campaign: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Campaign'
        }
    ]
});

var campaignSchema = new mongoose.Schema({
    name: String,
});


module.exports = {
    Partner: mongoose.model('Partner', partnerSchema),
    Product: mongoose.model('Product', productSchema),
    Campaign: mongoose.model('Campaign', campaignSchema)
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何在考虑引用的情况下从任何文档中删除对象(也许我应该以某种方式使用猫鼬填充)?例如,如果我要删除,Product那么我假设我还将也删除ref ID Partner和所有Campaigns属于this的引用ID Product

目前,我以这种方式删除:

var campSchema = require('../model/camp-schema');

    router.post('/removeProduct', function (req, res) {
            campSchema.Product.findOneAndRemove({ _id: req.body.productId }, function …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongoose-populate

1
推荐指数
1
解决办法
5242
查看次数

Mongoose populate 不是一个函数

我希望帖子的创建者是用户架构。所以我有2个模式

后.js

const mongoose=require('mongoose');
mongoose.Promise = global.Promise;
const Schema= mongoose.Schema;

const postSchema= new Schema({
    body:{ type: String, required:true, validate:bodyValidators},
    createdBy: { type: Schema.Types.ObjectId,ref:'User'}, // this one
    to: {type:String, default:null },
    createdAt: { type:Date, default:Date.now()},
    likes: { type:Number,default:0},
    likedBy: { type:Array},
    dislikes: { type:Number, default:0},
    dislikedBy: { type:Array},
    comments: [
        {
            comment: { type: String, validate: commentValidators},
            commentator: { type: String}
        }
    ]
});



module.exports = mongoose.model('Post',postSchema);
Run Code Online (Sandbox Code Playgroud)

用户.js

const mongoose=require('mongoose');
mongoose.Promise = global.Promise;
const Schema= mongoose.Schema;

const userSchema=new Schema({
    email: { …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongoose-populate

1
推荐指数
1
解决办法
5921
查看次数

猫鼬嵌套模型

不确定这是否会被视为重复,但我已经四处搜索并实现了与我在网上找到的类似查询,但似乎无法让我的嵌套引用起作用。我只是测试以了解用于填充嵌套引用和嵌套文档的猫鼬语法,如下所述:猫鼬嵌套模式与嵌套模型

但是,我一定错过了一些东西,因为它似乎可以工作,但返回一个空的嵌套引用数组。我知道我的查询应该返回嵌套引用的两个结果。

  • 我忽略了什么或做错了什么?
  • 如果我想使用嵌套文档,我将如何以不同的方式运行查询?

数据:

结果收集:

{
    "_id" : ObjectId("5a4dcbe4ab9a793d888c9396"),
    "event_id" : ObjectId("5a482302a469a068edc004e3"),
    "event_name" : "Sample Event",
    "score" : "3-2",
    "winner" : "player1"
},

{
    "_id" : ObjectId("5a59791379cc1c321c1918f0"),
    "event_id" : ObjectId("5a482302a469a068edc004e3"),
    "event_name" : "Sample Event",
    "score" : "2-1",
    "winner" : "player2"
}
Run Code Online (Sandbox Code Playgroud)

活动合集:

{
    "_id" : ObjectId("5a482302a469a068edc004e3"),
    "type" : "Tournament",
    "name" : "Sample Event"
}
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

var mongoose = require("mongoose");
mongoose.connect("MongoDB://localhost/devDB");

var ResultSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    event_id: {type: mongoose.Schema.Types.ObjectId, ref: "EventModel"},
    event_name: String,
    score: String,
    winner: String
}); …
Run Code Online (Sandbox Code Playgroud)

mongoose node.js mongoose-populate mongoose-schema

1
推荐指数
1
解决办法
2565
查看次数

猫鼬填充返回[对象]而不是结果

我对猫鼬的人口方法有疑问。遵循以下结构

const CompanySchema = new Schema({
  name: String,
  logo: String,
  description: String,
  address: String,
  website: String,
  phone: String,
  email: String,
  warehouses: [{ type: Schema.Types.ObjectId, ref: 'CompanyWarehouses' }],
});

const CompanyWarehouses = new Schema({
  company: { type: Schema.Types.ObjectId, ref: 'Company' },
  city: String,
});
Run Code Online (Sandbox Code Playgroud)

我在两个表中都有一些条目。我试图使用Populationfrom Mongoose来填充warehouses每个公司的字段。

使用以下查询

Company.find({}, 'warehouses -_id')
  .populate({
    path: 'warehouses',
  })
  .exec((err, docs) => {
     console.log(docs);
  }); 
Run Code Online (Sandbox Code Playgroud)

我得到以下结果

[ { warehouses: [ [Object], [Object], [Object] ] },
  { warehouses: [ [Object], [Object] ] …
Run Code Online (Sandbox Code Playgroud)

mongoose mongoose-populate

1
推荐指数
1
解决办法
286
查看次数

匹配猫鼬填充中的特定值

以下是用户集合的架构:

const Mongoose = require('mongoose')

const Schema = Mongoose.Schema

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String
    },
    supporterOf: [{
        type: Schema.Types.ObjectId,
        ref: 'individual',
        required: false
    }],
})

module.exports = Mongoose.model('user', userSchema);
Run Code Online (Sandbox Code Playgroud)

我想填充“supporterOf”,它是个人的集合(参考:个人)。'supporterOf' 包含一个 ObjectId 数组。我遇到了将特定 objectId 与该 ObjectId 数组匹配的问题。谁能建议我如何将特定的 ObjectId 与填充函数中的 ObjectIds 数组匹配?

populate mongoose mongodb node.js mongoose-populate

1
推荐指数
1
解决办法
1万
查看次数

Mongoose 填充不适用于 nextjs 应用程序。架构尚未注册

我一直在尝试使用课程文档填充 LessonIds 列表。但我收到错误,

Schema hasn't been registered for model \"Lesson\".\nUse mongoose.model(name, schema)

if (req.method === "GET") {
    Course.findById(courseId)
        .populate('lessons').then(course => {
            res.json(course);
        }).catch(err => {
            res.json({ error: err.title + ' : ' + err.message });
        });
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我导入注册了 LessonSchema 的 Lesson 模型,代码就可以工作。但我没有直接使用此文件中的课程模型,因此我发现很奇怪,我必须导入一些我不会使用的东西,只是为了使其他一些功能正常工作。有适当的方法吗?或者以某种方式在数据库连接时注册所有模型?

谢谢你!

mongoose mongoose-populate next.js

1
推荐指数
1
解决办法
1251
查看次数

排序mongoose 3.x填充文档的正确语法

我有两个MongoDB的集合CustomerUser1:1关系.我正在尝试使用Mongoose Population查询这两个文档并对其进行排序User.name.

以下没有任何工作.我的猫鼬是3.8.19.

Customer
    .find({})
    .populate("user", "name email phone")
    .sort({ "name": 1 })
    .exec()

Customer
    .find({})
    .populate("user", "name email phone", null, { sort: { 'name': 1 } } )
    .exec()

Customer
    .find({})
    .populate({
        path: "user",
        select: "name email phone",
        options: { sort: { "name": 1 }}
    }).
    exec()

Customer
    .find({})
    .populate({
        path: "user",
        select: "name email phone",
        options: { sort: [{ "name": 1 }]}
    })
    .exec()
Run Code Online (Sandbox Code Playgroud)

我找到了如何在查找请求中对填充的文档进行排序?,但对我来说没有成功.

这将是SQL中的下面内容: …

sorting mongoose mongodb node.js mongoose-populate

0
推荐指数
1
解决办法
2126
查看次数

如何仅查看猫鼬中的值的第一个字母来查找所有文档

我想按首字母查找所有文档。

情况是当我在mysql中查询时我可以做 WHERE Stores LIKE 'a%'

the result would be all data with the first letter a.
Run Code Online (Sandbox Code Playgroud)

问题是:

  • 如何使同样的query使用mongoose
  • 怎么样case-sensitive eg: (a,A)。这将是相同的查询与否?
  • 是否有必要lowercase_field为这种情况创建?

mongoose mongodb mongodb-query mongoose-populate mongoose-schema

0
推荐指数
1
解决办法
1520
查看次数

猫鼬与第三级嵌套字段值进行比较

我有以下收藏: 在此处输入图片说明

我想从collection1一直到Collection 3和4进行查找,以在一个查询中比较名称。

例:

collection1.find({
    collection2.collection3.name: req.body.name3,
    collection2.collection4.name: req.body.name4
}).exec()
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongoose-populate mongoose-schema

0
推荐指数
1
解决办法
91
查看次数