我的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 …
我有两个模式,
一个用于用户,另一个用于发布
在用户模式中,我有一个 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) 这是我的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) 我希望帖子的创建者是用户架构。所以我有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) 不确定这是否会被视为重复,但我已经四处搜索并实现了与我在网上找到的类似查询,但似乎无法让我的嵌套引用起作用。我只是测试以了解用于填充嵌套引用和嵌套文档的猫鼬语法,如下所述:猫鼬嵌套模式与嵌套模型
但是,我一定错过了一些东西,因为它似乎可以工作,但返回一个空的嵌套引用数组。我知道我的查询应该返回嵌套引用的两个结果。
数据:
结果收集:
{
"_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) 我对猫鼬的人口方法有疑问。遵循以下结构
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) 以下是用户集合的架构:
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 数组匹配?
我一直在尝试使用课程文档填充 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 模型,代码就可以工作。但我没有直接使用此文件中的课程模型,因此我发现很奇怪,我必须导入一些我不会使用的东西,只是为了使其他一些功能正常工作。有适当的方法吗?或者以某种方式在数据库连接时注册所有模型?
谢谢你!
我有两个MongoDB的集合Customer和User在1: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中的下面内容: …
我想按首字母查找所有文档。
情况是当我在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
我想从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)