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()
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19