mongodb - 关联字段
Posted 武卡卡的个人博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongodb - 关联字段相关的知识,希望对你有一定的参考价值。
1,博客表结构 Blog.js
var mongoose = require(‘mongoose‘)
mongoose.connect(‘mongodb://localhost/test‘,{ useUnifiedTopology: true , useNewUrlParser: true});
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
},
sort:{
type: mongoose.Schema.Types.ObjectId, ref: ‘Sort‘
}
});
var Blog = mongoose.model(‘Blog‘, blogSchema);
module.exports = Blog
2,分类表结构 Sort.js
var mongoose = require(‘mongoose‘)
mongoose.connect(‘mongodb://localhost/test‘,{ useUnifiedTopology: true , useNewUrlParser: true});
var Schema = mongoose.Schema;
var sortSchema = new Schema({
name:{type:String}
});
var Sort = mongoose.model(‘Sort‘, sortSchema);
module.exports = Sort
3,操作文件 api.js
const Blog = require(‘./Blog‘);
const Sort = require(‘./Sort‘);
async function cz(){
var sort1 = await Sort.findOne({name:"css"})
var blog1 = await Blog.find().populate(‘sort‘)
blog1.sort = sort1
await blog1.save()
}
cz()
以上是关于mongodb - 关联字段的主要内容,如果未能解决你的问题,请参考以下文章