gpt4 book ai didi

node.js - 如何在模式数组中发布和更新模式并打印它?

转载 作者:可可西里 更新时间:2023-11-01 10:42:21 25 4
gpt4 key购买 nike

你好,我是 node js 和 mongoose 的新手我有两个方案,我想在另一个方案中有方案对象 我的计划

用户.js

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Genre = require('../Models/genre');

// create a schema
var userSchema = new Schema({
name: { type: String, required: true, unique: true , index:true},
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: String,
gender: String,
genres: [{type: Schema.ObjectId, ref: Genre.Genre}] //this is the genre schema - the user can have many genres
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;

也曾尝试过

genres: [{type: Schema.Type.ObjectId, ref: Genre.Genre}]
and genres: ['Genre']

和 genre.js

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

// create a schema
var genreSchema = new Schema({
name: { type: String, required: true, unique: true, index: true },
age: String,
gender: String
});

// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);

// make this available to our genres in our Node applications
module.exports = Genre;

首先我想知道这样做是否可行?有更好的方法吗?

当我通过 postman 发布用户时,用户正在添加,但我没有得到完整的类型,我不知道它是否保存正确

这是我发布的json

{
"name":"erez",
"age": "23",
"password":"erez1234",
"email":"erez@erez.com",
"gender":"Male",
"genres": ["57285fe32c3c15e40c000001"] /// what should be here? is it right?
}

这是获取用户的json

[
{
"_id": "572874be9b43cb4834000002",
"name": "erez",
"age": "23",
"password": "yaniv1234",
"email": "erez@beatman.com",
"gender": "Male",
"__v": 0,
"genres": [
"57285fe32c3c15e40c000001"
]
}
]

如果是对的如何在获取用户时发送所有类型的完整用户?

希望我足够清楚

感谢帮助者

最佳答案

定义引用时,ref 属性必须与模型定义中的模型名称完全匹配,否则会出错。 ref 值应该是一个字符串,而不是像你所做的那样是一个对象,所以正确的方法应该是

genres: [{type: Schema.ObjectId, ref: 'Genre'}] 

当您读取数据时,Mongoose population 通过其 populate() 使文档读取变得非常简单。 功能。因此,例如,要显示特定用户的引用流派,请调用 populate() 以字符串中该字段的名称作为参数的方法,例如

User.findOne({"name": "Tom"})
.populate("genres")
.exec(err, user) { ... }

关于node.js - 如何在模式数组中发布和更新模式并打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com