下面是我的模型。我想将片段集合中的数据填充到我的流中。
流:
var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
// Declare schema
var streamSchema = Schema({
user_id: {
type: String,
required: true
},
public_key: {
type: String
},
private_key: {
type: String
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
particle: [{
type: Schema.Types.ObjectId,
ref: 'Piece'
}],
created_at: {
type: Date,
default: Date.now,
index: 1 // Note 1
},
});
streamSchema.plugin(mongoosePaginate);
// Export schema
// Model.paginate()
mongoose.model("Stream", streamSchema);
片:
var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');
// Declare schema
var pieceSchema = new mongoose.Schema({
stream_id: {
type: String,
required: true
},
particle: {
type: Object
},
order: {
type: Number,
default: 1
},
entries_number: {
type: Number,
default: 0
},
last_entry_at: {
type: Date
},
created_at: {
type: Date,
default: Date.now,
index: 1 // Note 1
},
});
pieceSchema.plugin(mongoosePaginate);
// Export schema
// Model.paginate()
mongoose.model("Piece", pieceSchema);
我的查询:
Stream
.findOne({
public_key: publicKey
})
.select("-data -weather -location")
.populate('particle', 'particle') // only return the particle
.exec(function (err, stream) {
if (err) return handleError(err);
console.log(stream);
});
结果:
{ _id: 580f69e0922112dd54a9f4e1,
user_id: '579f52bc53d9e8cc14f504da',
title: 'Dustbox 108',
description: '....',
public_key: 'HIGENfU96Hejy7y',
private_key: 'RcWrwGaGpDVHO4WQ',
alias: 'dustbox_108',
__v: 0,
created_at: 2016-10-25T14:19:12.008Z,
particle: []
}
结果我追求:
{ _id: 580f69e0922112dd54a9f4e1,
user_id: '579f52bc53d9e8cc14f504da',
title: 'Dustbox 108',
description: '....',
public_key: 'HIGENfU96Hejy7y',
private_key: 'RcWrwGaGpDVHO4WQ',
alias: 'dustbox_108',
__v: 0,
created_at: 2016-10-25T14:19:12.008Z,
particle: [{
"timestamp" : [
1490385416748.0,
1490385457814.0
],
"PM" : [
null,
null
],
"Particles" : [
"100",
"100"
]
}]
}
可能吗?
这是Piece模型的示例文件:
{
"_id" : ObjectId("58d57a08b2541e37c7fe5827"),
"stream_id" : "580f69e0922112dd54a9f4e1",
"particle" : {
"timestamp" : [
1490385416748.0,
1490385457814.0
],
"PM" : [
null,
null
],
"Particles" : [
"100",
"100"
]
},
"created_at" : ISODate("2017-03-24T19:56:56.735Z"),
"entries_number" : 2,
"order" : 1,
"__v" : 0,
"last_entry_at" : ISODate("2017-03-24T19:57:37.814Z")
}
有任何想法吗?
编辑:
最新输出:
...
particle: [ { _id: 58d57a08b2541e37c7fe5827, particle: [Object] } ],
...
仍然不是我要找的东西。
最佳答案
因为“粒子”字段是指子文档的字段,它本身就是一个对象,所以您必须在两个级别上进行填充。
.populate({
path: 'particle',
populate: { path: 'piece.particle' }
})
请参阅文档(跨多个级别填充):http://mongoosejs.com/docs/populate.html
关于node.js - Mongoose 填充多个文件不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43008347/